Python 如何在matplotlib中使用ax.get_ylim()

Python 如何在matplotlib中使用ax.get_ylim(),python,matplotlib,axes,Python,Matplotlib,Axes,我执行以下导入操作: import matplotlib.pyplot as plt import matplotlib.axes as ax import matplotlib import pylab 它正确地执行 plt.plot(y1, 'b') plt.plot(y2, 'r') plt.grid() plt.axhline(1, color='black', lw=2) plt.show() 并显示了图表 但如果我插入 print("ylim=", ax.get_ylim())

我执行以下导入操作:

import matplotlib.pyplot as plt
import matplotlib.axes as ax
import matplotlib
import pylab
它正确地执行

plt.plot(y1, 'b')
plt.plot(y2, 'r')
plt.grid()
plt.axhline(1, color='black', lw=2)
plt.show()
并显示了图表

但如果我插入

print("ylim=", ax.get_ylim())
我收到错误消息:

AttributeError:“模块”对象没有属性“get_ylim”

我试过更换斧头。使用plt、matplotlib等,我得到了相同的错误


调用
get_ylim
的正确方法是什么?

不要导入
matplotlib.axes
,在您的示例中,您只需要导入
matplotlib.pyplot

get_ylim()
是matplotlib.axes.axes
类的一种方法。如果使用pyplot打印某些内容,则始终会创建此类。它表示坐标系,并具有所有方法将某些内容绘制到坐标系中并对其进行配置

在您的示例中,没有称为ax的轴,您将matplotlib.Axes模块命名为ax

要获取matplotlib当前使用的轴,请使用
plt.gca()。获取_ylim()

或者你可以这样做:

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()

如果您只想使用pyplot API:
plt.ylim()
也会精确地返回ylim。

+1。如果要使用
pyplot
pylab
,则无需导入
matplotlib.axes
。如果您想轻松获得轴对象,请使用图,ax=plt.subplot()
更短的将是plt.plt(y1)
打印(plt.gca().get_ylim())
。不需要任何ax。这在文本中;)