How to use ax.get_ylim() in matplotlib

user1067305 picture user1067305 · Aug 21, 2014 · Viewed 20.8k times · Source

I do the following imports:

import matplotlib.pyplot as plt
import matplotlib.axes as ax
import matplotlib
import pylab

It properly executes

plt.plot(y1, 'b')
plt.plot(y2, 'r')
plt.grid()
plt.axhline(1, color='black', lw=2)
plt.show()

and shows the graph.

But if I insert

print("ylim=", ax.get_ylim())

I get the error message:

AttributeError: 'module' object has no attribute 'get_ylim'

I have tried replacing ax. with plt., matplotlib, etc., and I get the same error.

What is the proper way to call get_ylim?

Answer

MaxNoe picture MaxNoe · Aug 21, 2014

Do not import matplotlib.axes, in your example the only import you need is matplotlib.pyplot

get_ylim() is a method of the matplotlib.axes.Axes class. This class is always created if you plot something with pyplot. It represents the coordinate system and has all the methods to plot something into it and configure it.

In your example, you have no Axes called ax, you named the matplotlib.axes module ax.

To get the axes currently used by matplotlib use plt.gca().get_ylim()

or you could do something like this:

fig = plt.figure()
ax = fig.add_subplot(1,1,1) # 1 Row, 1 Column and the first axes in this grid

ax.plot(y1, 'b')
ax.plot(y2, 'r')
ax.grid()
ax.axhline(1, color='black', lw=2)

print("ylim:" ax.get_ylim())

plt.show()

If you just want to use the pyplot API: plt.ylim() also returns the ylim.