【问题标题】:matplotlib data showing up on two seperate plotsmatplotlib 数据显示在两个单独的图上
【发布时间】:2020-05-22 18:29:41
【问题描述】:

我有一个包含此代码的组合线和条形图。 (剧情看起来不错)

fig, ax1 = plt.subplots(figsize=(25, 10))


ax2 = ax1.twinx()
ax1.bar(daily_summary.index, daily_summary['hour_max_demand'],width=20, alpha=0.2, color='orange')
ax1.grid(b=False) # turn off grid #2

ax2.plot(daily_summary.kW)
ax2.set_title('Max Demand per Day and Max Demand Hour of Day')
ax2.set_ylabel('Electric Demand kW')
ax1.set_ylabel('Hour of Day')

plt.savefig('./plots/Max_Demand_and_Max_Hour_of_Day.png')

但是在我的代码中再往下一点,我正在尝试绘制另一个 Pandas 数据框和上面的组合条形图和折线图,数据显示在其中...有人有什么提示可以尝试吗???

plot2 = daily_summary.kWH.rolling(7, center=True).mean()
plt.title(' 7 Day Rolling Average - kWH / Day')

plot2.plot(figsize=(25,10))
plt.savefig('./plots/kWhRollingAvg.png')

黄色条形图数据不应在此处仅位于底部的一行:

【问题讨论】:

  • 如果你想拥有另一个图形,你需要创建它:) fig2, ax3 = plt.subplots(figsize=(25, 10))ax3.plot(...); fig2.savefig(...)。另外,请记住它是千瓦时而不是千瓦时(H 代表亨利)。
  • Gotchya.. 也感谢 kWh 小费。如果您发布答案,请点击绿色复选标记

标签: python pandas matplotlib


【解决方案1】:

一般来说,最好使用面向对象的方法,因为plt.something() 在添加轴和图形时会变得越来越难以预测。

对于您的具体问题,您需要定义一个新图形及其关联的斧头,否则看起来像 df.plot(...) 的调用默认为不一定是您想要的斧头。

# First figure.
fig1, ax1 = plt.subplots(figsize=(25, 10))    
ax2 = ax1.twinx()

ax1.bar(daily_summary.index, daily_summary['hour_max_demand'], width=20, alpha=0.2, color='orange')
ax1.grid(b=False) # turn off grid #2

ax2.plot(daily_summary.kW)
ax2.set_title('Max Demand per Day and Max Demand Hour of Day')
ax2.set_ylabel('Electric Demand kW')
ax1.set_ylabel('Hour of Day')

fig1.savefig('./plots/Max_Demand_and_Max_Hour_of_Day.png')

# Figure 2.
fig2, ax3 = plt.subplots(figsize=(25, 10))
ax3.title(' 7 Day Rolling Average - kWh / Day')
data3 = daily_summary.kWH.rolling(7, center=True).mean()
ax3.plot(data3)
fig2.savefig('./plots/kWhRollingAvg.png')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多