bbartling
bbartling

Reputation: 3494

matplotlib data showing up on two seperate plots

I have a combined line & bar plot with this code. (plot works looks good)

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')

enter image description here

But a little further down in my code I am attempting another plot of a Pandas dataframe and the combined bar & line chart above, the data is showing up in it... Would anyone have any tips to try???

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')

The yellow bar chart data should not be on here only the one line towards the bottom: enter image description here

Upvotes: 0

Views: 46

Answers (1)

Guimoute
Guimoute

Reputation: 4629

In general, it is better to use the object-oriented methods because plt.something() gets more and more impredictable as you add axes and figures.

For your specific problem, you need to define a new figure and its associated ax, otherwise the calls looking like df.plot(...) default to an ax that is not necessarily the one you want.

# 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')

Upvotes: 1

Related Questions