【问题标题】:Plot several plots together as subplots [duplicate]将多个图一起绘制为子图[重复]
【发布时间】:2021-12-21 02:45:28
【问题描述】:

我尝试绘制多个带有多个数据系列的图作为子图。

import pandas as pd
import matplotlib.pyplot as plt

df1 = pd.DataFrame({
    'Date':['2021-01-01', '2021-01-02', '2021-01-03', '2021-01-04', '2021-01-05'],
    'index':[0, 1, 2, 3, 4], 
    '02K W':[3.5, 0.1, 3, 'nan', 0.2], 
    '03K W':[4.2, 5.2, 2.5, 3.0, 0.6], 
    '04K W':[1.5, 2.6, 8.2, 4.2, 5.3]}) 

df2 = pd.DataFrame({
    'Date':['2021-01-01', '2021-01-02', '2021-01-03', '2021-01-04', '2021-01-05'],
    'index':[0, 1, 2, 3, 4], 
    '02K W':[3, 'nan', 5, 3, 5.2], 
    '03K W':[2.1, 2.9, 2.5, 3.9, 6.7], 
    '04K W':[1.8, 6.2, 5, 2.5, 3.7]}) 

df1['Date'] = pd.to_datetime(df1['Date'])
df1 = df1.set_index('index')

for col in df1.columns[1:]:
    plt.plot(df1['Date'], df1[col])

目前,我只能绘制第一个图,我不确定如何将 for loop 分配给 y 轴。

fig, (ax1, ax2) = plt.subplots(1, 2)
ax1.plot(df1['Date'], y)
ax2.plot(df2['Date'], y)

非常感谢您的建议。

【问题讨论】:

    标签: python pandas dataframe matplotlib


    【解决方案1】:

    您不需要遍历所有列。相反,直接解析它们。看看这个:

    import pandas as pd
    
    import matplotlib.pyplot as plt
    
    df1 = pd.DataFrame({
        'Date':['2021-01-01', '2021-01-02', '2021-01-03', '2021-01-04', '2021-01-05'],
        'index':[0, 1, 2, 3, 4], 
        '02K W':[3.5, 0.1, 3, 'nan', 0.2], 
        '03K W':[4.2, 5.2, 2.5, 3.0, 0.6], 
        '04K W':[1.5, 2.6, 8.2, 4.2, 5.3]}) 
    
    df2 = pd.DataFrame({
        'Date':['2021-01-01', '2021-01-02', '2021-01-03', '2021-01-04', '2021-01-05'],
        'index':[0, 1, 2, 3, 4], 
        '02K W':[3, 'nan', 5, 3, 5.2], 
        '03K W':[2.1, 2.9, 2.5, 3.9, 6.7], 
        '04K W':[1.8, 6.2, 5, 2.5, 3.7]}) 
    
    df1['Date'] = pd.to_datetime(df1['Date'])
    df1 = df1.set_index('index')
    df2['Date'] = pd.to_datetime(df2['Date'])
    df2 = df2.set_index('index')
    
    fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(25,8))
    plot1 = ax1.plot(df1['Date'], df1[df1.columns[1:]])
    ax1.set_xlabel('Date')
    ax1.set_ylabel('W')
    plot2 = ax2.plot(df2['Date'], df2[df2.columns[1:]])
    ax2.set_xlabel('Date')
    ax2.set_ylabel('W')
    
    ax1.legend(plot1, df1.columns[1:])
    ax2.legend(plot2, df2.columns[1:])
    plt.show()
    

    【讨论】:

    • 非常感谢这种替代方法!
    【解决方案2】:

    这是你要找的吗?

    fig, (ax1, ax2) = plt.subplots(1, 2)
    for col in df1.columns[1:]:
        ax1.plot(df1['Date'], df1[col])
        ax2.plot(df2['Date'], df2[col])
    

    【讨论】:

      【解决方案3】:

      为了避免必须使用轴语法,您可以做的事情是调用plt.sca(ax),它将当前轴设置为ax。这非常简洁,因为您可以明确设置要使用的轴。

      fig, (ax1, ax2) = plt.subplots(1, 2)
      plt.sca(ax1)
      plt.plot.plot(df1['Date'], y)
      plt.sca(ax2)
      plt.plot(df2['Date'], y)
      

      有很多方法可以导航 matplotlib,我发现上述方法很直观。

      【讨论】:

      • 非常感谢您的建议
      猜你喜欢
      • 1970-01-01
      • 2019-06-05
      • 2018-01-16
      • 2012-06-26
      • 1970-01-01
      • 2021-04-06
      • 1970-01-01
      • 2020-04-28
      • 1970-01-01
      相关资源
      最近更新 更多