【问题标题】:Setting Yaxis in Matplotlib using Pandas使用 Pandas 在 Matplotlib 中设置 Yaxis
【发布时间】:2013-07-21 04:12:54
【问题描述】:

使用 Pandas 在 I-Python Notebook 中绘图,我有几个绘图,因为 Matplotlib 决定 Y 轴,所以设置它们的方式不同,我们需要使用相同的范围比较这些数据。 我已经尝试了几种变体:(我假设我需要将限制应用于每个情节..但由于我无法让一个工作......从 Matplotlib 文档看来我需要设置 ylim,但可以'不知道这样做的语法。

df2250.plot(); plt.ylim((100000,500000)) <<<< if I insert the ; I get int not callable and  if I leave it out I get invalid syntax. anyhow, neither is right...
df2260.plot()
df5.plot()

【问题讨论】:

    标签: matplotlib pandas ipython-notebook


    【解决方案1】:

    pandas plot() 返回坐标轴,你可以用它来设置ylim。

    ax1 = df2250.plot()
    ax2 = df2260.plot()
    ax3 = df5.plot()
    
    ax1.set_ylim(100000,500000)
    ax2.set_ylim(100000,500000)
    etc...
    

    您还可以将轴传递给 Pandas 绘图,因此可以将其绘制在相同的轴上,如下所示:

    ax1 = df2250.plot()
    df2260.plot(ax=ax1)
    etc...
    

    如果您想要很多不同的图,预先定义轴并在一个图形内可能是给您最大控制权的解决方案:

    fig, axs = plt.subplots(1,3,figsize=(10,4), subplot_kw={'ylim': (100000,500000)})
    
    df2260.plot(ax=axs[0])
    df2260.plot(ax=axs[1])
    etc...
    

    【讨论】:

    • 您也可以将sharey=True 添加到plt.subplots。然后,即使您放大特定的子图,y 限制也将保持不变。
    【解决方案2】:

    我猜这是 2013 年接受此答案后添加的功能; DataFrame.plot() 现在公开了一个 ylim 参数来设置 y 轴范围:

    df.plot(ylim=(0,200))

    详情请见pandas documentation

    【讨论】:

      猜你喜欢
      • 2012-05-11
      • 2012-03-30
      • 2017-03-11
      • 1970-01-01
      • 2021-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多