首页 文章

在matplotlib中自动缩放,在同一图表中绘制不同的时间序列

提问于
浏览
1

我有一个'主'熊猫数据帧,它有几个术语的'极性'值的时间序列 . 我想与其中的4个一起工作,所以我提取了4个独立的数据帧,包含时间序列(所有术语的时间序列相同,但极性值不同 . )

我使用下面的代码将它们绘制在4个单独的matplotlib图中

fig, axes = plt.subplots(nrows=2, ncols=2)
polarity_godzilla.plot(ax=axes[0,0]); axes[0,0].set_title('Godzilla')
polarity_henry_kissinger.plot(ax=axes[0,1]); axes[0,1].set_title('Henry Kissinger')
polarity_bmwi.plot(ax=axes[1,0]); axes[1,0].set_title('BMWi')
polarity_duran_duran.plot(ax=axes[1,1]); axes[1,1].set_title('Duran Duran')

现在,我想将它们全部绘制在同一个图形中,以便我了解每个图形的大小,因为matplotlib的自动缩放可以通过查看图形给出关于幅度的错误印象 .
enter image description here

两个问题:1)绘图时是否有办法设置Y轴的最小值和最大值? 2)我不是matplotlib的专家,所以我不知道如何使用不同的颜色,标记,标签等在同一个图中绘制4个变量 . 我试过nrows = 1,ncols = 1但是不能绘制任何东西 .

谢谢

2 回答

  • 1

    axes[i,j].set_ylim([min,max], auto=False) 将在 i,j 图中设置绘图的y限制 . auto=False 阻止它破坏你的设置 .

    您可以通过调用 plt.hold(True) ,绘制一堆图,然后调用 plt.show()plt.savefig(filename) 来在同一图上绘制多条线 .

    您可以将颜色代码作为第三个位置参数传递给 plt.plot() . 语法有点拜占庭(在matplotlib.pyplot.plot文档中记录了's inherited from MATLAB); it' . 您可以将此参数传递给 DataFrame.plot (例如) style='k--' .

    对于你的情况,我会尝试

    fig, ax = plt.axes()
    plt.hold(True)
    polarity_godzilla.plot(ax=ax, style="k-o", label="Godzilla")
    polarity_henry_kissinger(ax=ax, style="b-*", label="Kissinger")
    #etc.
    plt.legend()  #to draw a legend with the labels you provided
    plt.show() #or plt.savefig(filename)
    
  • 1

    您可以循环到 AxesSubplot 对象并调用 autoscale 传递 axis 参数:

    for ax in axes:
        ax.autoscale(axis='y')
    

相关问题