【问题标题】:How can I recreate this plot of a pandas DataFrame, line and bar如何重新创建熊猫 DataFrame、线条和条形图
【发布时间】:2020-12-19 07:40:04
【问题描述】:

之前我设法创建了以下情节

import pandas as pd
import matplotlib.pyplot as plt

df_prog = pd.DataFrame({"Prognos tim": [2, 3, 3]})
df_prog.index = pd.date_range(start='2020-01-01 00', end='2020-01-01 02', freq='H')
df_prog.index = df_prog.index + pd.Timedelta(minutes=30)

现在我试图再次创建这个情节但没有成功。我的记忆力下降了

我试过了

ax = df_prog.plot(kind='bar')
df_prog.plot(kind='line')

Plot Pandas DataFrame as Bar and Line on the same one chart中所述

但是根据首先选择的是条形还是线形,只显示一个,而不是两个都在同一个图中。

【问题讨论】:

    标签: python pandas matplotlib


    【解决方案1】:

    您在line plot function 中缺少ax=axuse_index=False 参数。这将在与条形图相同的图中绘制线,并防止线图使用 x 轴的时间戳。相反,x 轴单位将从零开始,就像条形图一样,因此线条与条形对齐。无需转换索引,无需matplotlib。

    import pandas as pd # v 1.1.3
    
    # Create sample dataset
    idx = pd.date_range(start='2020-01-01 00:30', periods=3, freq='60T')
    df_prog = pd.DataFrame({"Prognos tim": [2, 3, 3]}, index=idx)
    
    # Combine pandas line and bar plots
    ax = df_prog.plot.bar(figsize=(8,5))
    df_prog.plot(use_index=False, linestyle='-', marker='o', color='r', ax=ax)
    
    # Format labels
    ax.set_xticklabels([ts.strftime('%H:%M') for ts in df_prog.index])
    ax.figure.autofmt_xdate(rotation=0, ha='center')
    


    如果省略 use_index=False 参数,条形图和线形图仍会绘制在同一图中,只是 x 限制受限于您创建的第二个图。例如,您可以在此处看到:

    ax = df_prog.plot.bar(figsize=(8,5))
    df_prog.plot(linestyle='-', marker='o', color='r', ax=ax) # plot line in bars plot
    ax.set_xlim(-0.5,2.5); # the bars are here
    # ax.set_xlim(26297300, 26297450); # the line is here, the values are pandas period units
    

    【讨论】:

      【解决方案2】:

      您需要将时间轴转换为字符串。然后你可以将它们绘制在一起。

      import pandas as pd
      import matplotlib.pyplot as plt
      
      df_prog = pd.DataFrame({"Prognos tim": [2, 3, 3]})
      df_prog.index = pd.date_range(start='2020-01-01 00', end='2020-01-01 02', freq='H')
      df_prog.index = df_prog.index + pd.Timedelta(minutes=30)
      
      _, ax = plt.subplots()
      df_prog.index = df_prog.index.astype(str)
      df_prog.plot(kind='line', linestyle='-', marker='o', color='r', ax=ax)
      df_prog.plot(kind='bar', ax=ax)
      
      plt.show()
      

      【讨论】:

      • 这是 Pandas 的新变化,混合条形图和折线图要求 x 轴为字符串类型?
      猜你喜欢
      • 1970-01-01
      • 2021-06-16
      • 2017-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-11
      相关资源
      最近更新 更多