Plot logarithmic axes with matplotlib in python
You can use the
Axes.set_yscale method. That allows you to change the scale after the
Axes object is created. That would also allow you to build a control to let the user pick the scale if you needed to.
The relevant line to add is:
You can use
'linear' to switch back to a linear scale. Here's what your code would look like:
import pylabimport matplotlib.pyplot as plta = [pow(10, i) for i in range(10)]fig = plt.figure()ax = fig.add_subplot(2, 1, 1)line, = ax.plot(a, color='blue', lw=2)ax.set_yscale('log')pylab.show()
First of all, it's not very tidy to mix
pyplot code. What's more, pyplot style is preferred over using pylab.
Here is a slightly cleaned up code, using only
from matplotlib import pyplota = [ pow(10,i) for i in range(10) ]pyplot.subplot(2,1,1)pyplot.plot(a, color='blue', lw=2)pyplot.yscale('log')pyplot.show()
The relevant function is
pyplot.yscale(). If you use the object-oriented version, replace it by the method
Axes.set_yscale(). Remember that you can also change the scale of X axis, using
Check my question What is the difference between ‘log’ and ‘symlog’? to see a few examples of the graph scales that matplotlib offers.