Plotting Stacked Bars With A Total Line And Dates On Xlabels
I am using the pandas plot to generate a stacked bar chart, which has a different behaviour from matplotlib's, but the dates always come out with a bad format and I could not chang
Solution 1:
Is this what you want:
fig, ax = plt.subplots(1,1, figsize=(16,9))
# PLOTTING
ax.bar(df.index, df['price ex sa'], bottom=df['quantum ex sa'],width=31, label='price ex sa')
ax.bar(df.index, df['quantum ex sa'], width=31, label='quantum ex sa')
total = df.sum(axis=1)
ax.plot(total.index, total, color='r', linewidth=3, label='total')
ax.legend()
plt.show()
Edit: There seems to be a bug (features) on plotting with datetime. I tried to convert the index to string and it works:
df.index=df.index.strftime('%Y-%m')
ax = df.plot(kind='bar', stacked=True, width=1)
df['Total'] = df.sum(axis=1)
df['Total'].plot(ax=ax, label='total')
ax.legend()
Edit 2: I think I know what's going on. The problem is that
ax = df.plot(kind='bar', stacked=True)
returns/sets x-axis of ax
to range(len(df))
labeled by the corresponding values from df.index
, but not df.index
itself. That's why if we plot the second series on the same ax
, it doesn't show (due to different scale of xaxis). So I tried:
# PLOTTING
colums = df.columns
ax = df.plot(kind='bar', stacked=True, width=1, figsize=(10, 6))
ax.plot(range(len(df)), df.sum(1), label='Total')
ax.legend()
plt.show()
and it works as expected
Post a Comment for "Plotting Stacked Bars With A Total Line And Dates On Xlabels"