【问题标题】:How to use ax.get_ylim() in matplotlib如何在 matplotlib 中使用 ax.get_ylim()
【发布时间】:2014-10-14 13:02:46
【问题描述】:

我做了以下导入:

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: 'module' 对象没有属性 'get_ylim'

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

拨打get_ylim的正确方法是什么?

【问题讨论】:

    标签: python matplotlib axes


    【解决方案1】:

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

    get_ylim() 是 matplotlib.axes.Axes class 的一个方法。如果您使用 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。

    【讨论】:

    • +1 精确。如果要使用pyplotpylab,则无需导入matplotlib.axes。如果您想轻松获取Axes 对象,请使用fig, ax = plt.subplots()
    • 更短的应该是plt.plot(y1)print(plt.gca().get_ylim())。不需要任何斧头。
    • 这是在文本中;)
    猜你喜欢
    • 2018-01-04
    • 2010-12-24
    • 2022-08-04
    • 2015-12-05
    • 2022-12-13
    • 2020-11-19
    • 2017-12-07
    • 2015-05-08
    • 2015-06-16
    相关资源
    最近更新 更多