How to use ax.get_ylim() in matplotlib
Asked Answered
P

1

9

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?

Proverbial answered 21/8, 2014 at 1:53 Comment(0)
J
12

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.

Jesseniajessey answered 21/8, 2014 at 5:17 Comment(3)
+1 precisely. It is unnecessary to import matplotlib.axes if you're going to use pyplot or pylab. If you want to get an Axes object easily, use fig, ax = plt.subplots()Saxhorn
Even shorter would be plt.plot(y1) print(plt.gca().get_ylim()). No need for any ax.Lohse
This is in the text ;)Jesseniajessey

© 2022 - 2024 — McMap. All rights reserved.