【问题标题】:Insert a pandas DataFrame plot into a matplotlib subplot将 pandas DataFrame 图插入 matplotlib 子图
【发布时间】:2014-08-29 03:29:52
【问题描述】:

我创建了一个包含 4 个子图的图,每个子图将显示对某些次声数据的不同类型的分析。这是我用来创建子图的代码:

gs = gridspec.GridSpec(2, 2, width_ratios=[1,1], height_ratios=[1,1])

ax1 = plt.subplot(gs[0])
ax2 = plt.subplot(gs[1])
ax3 = plt.subplot(gs[2])
ax4 = plt.subplot(gs[3])

到目前为止,我已经能够将我想要的内容输入到子图中,但是我希望能够将 pandas DataFrame 图输入到 ax3 中,但我似乎无法做到。我已经编写了 pandas 程序,正准备将其插入到更大的脚本中,以便在子图中显示。

这是用于绘制 pandas DataFrame 图的代码行:

df.plot(subplots=True, sharey=True, ylim=(0,(y_max*1.5)))

【问题讨论】:

    标签: python matplotlib pandas subplot


    【解决方案1】:

    使用pandas.Dataframe.plot 绘图时,您可以使用关键字参数ax 选择要绘图的Axes 对象,如下所示:

    gs = gridspec.GridSpec(2, 2, width_ratios=[1,1], height_ratios=[1,1])
    
    ax1 = plt.subplot(gs[0])
    ax2 = plt.subplot(gs[1])
    ax3 = plt.subplot(gs[2])
    ax4 = plt.subplot(gs[3])
    
    # ...some other code that defines df...
    
    df.plot(ax=ax3)
    

    这会将您的数据添加到ax3 对象。请注意,这会将您的所有列绘制到一个子图中,如果您想要一个特定的列,那么您可以使用df['my_col_name'].plot(ax=ax3)

    【讨论】:

    • 这真的很有帮助,谢谢。在我原来的 DataFrame 图中,它有 4 个数据子图,我似乎无法让它将其绘制到 ax3 中。有没有办法做到这一点?
    • 所以你希望在ax3 中有 4 个子图?或者 ax3 是 4 个子图之一,您希望自动将每个列绘制到 ax
    • 我想要 ax3 中的 4 个子图。绘制 df 的原始代码将其分为 4 个子图,但我似乎无法将 (ax=ax3) 部分添加到此。
    • 不幸的是,看起来选择 subplots 选项会覆盖您对 ax 的选择,我不知道有什么方法可以简单地克服这个问题。如果你想要不简单,那么你可以创建一个更复杂的 GridSpec 对象,它有 7 个 ax:三个将是 ax1、ax2 和 ax4,其余四个将是 ax3 当前所在的位置。
    猜你喜欢
    • 2019-10-04
    • 2020-08-12
    • 1970-01-01
    • 2021-05-18
    • 2014-03-24
    • 2019-07-25
    • 2013-12-24
    • 1970-01-01
    • 2018-08-13
    相关资源
    最近更新 更多