scrps93
scrps93

Reputation: 313

Pandas: Stacked bar plot with adjacent bars

Lets say I have the following Pandas dataframe:

>> df
Period   Income    Expenses   Commissions   
0        12034.23  1665.25    601.59
1        23432.77  2451.33    1521.4
2        62513.12  4210.35    3102.24

I'd like to make a stacked bar plot of Expenses and Commissions, and then have the Income column be an adjacent bar next to this stacked column.

I'm familiar with the df.plot.bar() method, but I'm not sure how to shift the x-axis values to have the Income bar adjacent to the stacked Expenses and Commissions bars

Upvotes: 1

Views: 633

Answers (1)

Sheldore
Sheldore

Reputation: 39042

You can do the following: First produce the stacked bar plot and then use shifted x-values, where the shift is equal to the stacked-bar width. Additionally, you can add the extra legend for Income using this method, if you wish

import matplotlib.patches as mpatches
import numpy as np

bar_width = 0.25

fig, ax = plt.subplots()
df[['Expenses', 'Commissions']].plot(kind='bar', stacked=True, ax=ax, width=bar_width)
ax.bar(np.arange(len(df))+bar_width, df['Income'], align='center', width=bar_width, color='green')
ax.set_xlim(-0.5, 2.5)


handles, labels = ax.get_legend_handles_labels()
patch = mpatches.Patch(color='green', label='Income')

handles.append(patch) 

plt.legend(handles=handles, loc='best')

enter image description here

Upvotes: 3

Related Questions