Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use ax.get_ylim() in matplotlib

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?

like image 898
user1067305 Avatar asked Aug 21 '14 01:08

user1067305


People also ask

How do I limit the y-axis in Python?

Make two variables for max and min values for Y-axis. Use ylim() method to limit the Y-axis range. Use bar() method to plot the bars. To display the figure, use show() method.

How do I change the y-axis values in Matplotlib?

To specify the value of axes, create a list of characters. Use xticks and yticks method to specify the ticks on the axes with x and y ticks data points respectively. Plot the line using x and y, color=red, using plot() method. Make x and y margin 0.

How do you get ax from PLT?

To get a list of axes of a figure, we will first create a figure and then, use get_axes() method to get the axes and set the labels of those axes. Create xs and ys using numpy and fig using figure() method.


1 Answers

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.

like image 103
MaxNoe Avatar answered Sep 28 '22 19:09

MaxNoe