Stacked Bar chart of many columns grouped by the values of one column

Question:

I have a Pandas dataframe like this

'BondInvestments' |'Cash' |'EquityInvestments'| 'MoneyMarketInvestments' | 'Cluster'
10                | 1     | 10                |  20                      | 0
10                | 3     | 10                |  20                      | 1
200               | 1     | 15                |  20                      | 1
10                | 1     | 10                |  10                      | 2
10                | 1     | 10                |  20                      | 0
13                | 3     | 10                |  20                      | 2
200               | 1     | 15                |  20                      | 1
10                | 1     | 10                |  10                      | 0

I would like to create a horizontal stacked bar chart grouped by ‘Cluster’. How can I do it in Python? I’d prefer using matplotlib but any other suggestion is welcome.

Asked By: coelidonum

||

Answers:

Use DataFrame.plot.barh:

df.set_index('Cluster').plot.barh(stacked=True)
Answered By: jezrael

if only the style you don’t satisfy, just try another style use plt.style.

import matplotlib.pyplot as plt
plt.style.use('fivethirtyeight')
plt.rc('figure', figsize = (10,4))
df.groupby('Cluster').sum().plot.barh(stacked=True)
plt.show()

enter image description here

Answered By: Ferris