如何在matplotlib中使用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的正确方法是什么?
Answers
不要导入matplotlib.axes,在您的示例中,您唯一需要的导入是matplotlib.pyplot
get_ylim()是 matplotlib.axes.Axesclass的一个方法。如果您使用 pyplot 绘制某些内容,则始终会创建此类。它代表坐标系,并具有将某些内容绘制到其中并对其进行配置的所有方法。
在您的示例中,您没有名为 ax 的轴,您将 matplotlib.axes 模块命名为 ax。
要获取 matplotlib 当前使用的轴,请使用plt.gca().get_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。
更多推荐

所有评论(0)