How to use ax.get_ylim() in matplotlib

23,248

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.

Share:
23,248
user1067305
Author by

user1067305

I started programming in 1964, with Fortran. I've programmed extensively in Fortran, 360 Assembler, PL/I, and especially C. I've also dabbled in Forth, APL, Prolog, Basic, & Java. Most recently I've been using javascript and perl. I'm new to python.

Updated on August 10, 2022

Comments

  • user1067305
    user1067305 over 1 year

    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?

  • Paul H
    Paul H over 9 years
    +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()
  • Matthias Arras
    Matthias Arras about 5 years
    Even shorter would be plt.plot(y1) print(plt.gca().get_ylim()). No need for any ax.
  • MaxNoe
    MaxNoe about 5 years
    This is in the text ;)