【问题标题】:Plotting a pandas dataframe as stacked barchart with matplotlib. How to get rid of the overlapping?使用 matplotlib 将 pandas 数据框绘制为堆积条形图。如何摆脱重叠?
【发布时间】:2016-02-18 21:13:43
【问题描述】:

我正在从 Pandas 数据框中绘制一年每小时数据的不同列。 我写了以下函数来绘制:

    def plotResults(dfA):
    fig, (ax1,ax2) = plt.subplots(2, sharex=True, sharey=False)

    ax1.plot(dfA.index, dfA['LP1'], color='blue',alpha=0.7, label='LP1')

    ax1.bar(dfA.index, dfA['b'], color='green',alpha=0.1, rwidth=1,  label='b') 
    ax1.bar(dfA.index, dfA['p'].fillna(0), color='red',alpha=0.1, rwidth=1, label='p', bottom=dfA['b'])
    ax1.legend(loc='best')
    ax2.plot(dfA.index, dfA['Residual'], color='red',alpha=0.7, label='LP1')
    ax2.legend(loc='best')

    plt.show()

由于某种我不明白的原因,条形图的条形重叠。我一直在尝试使用width = 1.0/(len(dfA.index)),但随后酒吧变得非常狭窄。

如何设置条形图,使它们不重叠并覆盖一小时(这是 dfA 的周期性)?

上图中的红色条之间应该有间隙。它们只有几个小时的值。

【问题讨论】:

    标签: python pandas matplotlib bar-chart


    【解决方案1】:

    我还没有找到关于条形图中重叠条的任何解决方案,但我找到了一种解决方法,可以为我解决问题。

    使用堆栈图代替条形图。

       def plotResults(dfA):
        fig, (ax1,ax2) = plt.subplots(2, sharex=True, sharey=False)
        # Upper Chart
        # Linechart
        ax1.plot(dfA.index, dfA['LP1'], color='blue',alpha=0.7, label='LP1')
        # stackplot
        ax1.stackplot(dfA.index,dfA['b'],dfA['p'], label=['b', 'p'], colors=['green','red'] )   #stackplot labels do not show in Legend
        ax1.plot([], [], color='red', label='p', linewidth=10)      #dummy plots only to show labels in the legend
        ax1.plot([], [], color='green', label='b', linewidth=10)    #dummy plots only to show labels in the legend
        ax1.legend(loc='best')
        # Lower Chart - Residuals
        ax2.plot(dfA.index, dfA['Residual'], color='red',alpha=0.7, label='Residual')
        ax2.legend(loc='best')
        plt.show()
    

    使用 stackplot 不是最初问题的答案,但它为我解决了问题。

    【讨论】:

      猜你喜欢
      • 2018-11-26
      • 2018-09-28
      • 1970-01-01
      • 2016-05-24
      • 2018-03-10
      • 2017-04-11
      相关资源
      最近更新 更多