Home > Mobile >  How to combine two categories of one column in not separate bars but one combined bar in a chart or
How to combine two categories of one column in not separate bars but one combined bar in a chart or

Time:10-15

I have a pandas dataframe in the following format:

df = pd.DataFrame([['A', 'Blue', 30], ['A', 'Red', 180], ['B', 'Blue', 50], ['B', 'Red', 340], ['C', 'Blue', 70], ['C', 'Red', 930]])
df.columns = ['Type', 'Color', 'Count']

df:

   Type Color  Count
0    A  Blue     30
1    A   Red    180
2    B  Blue     50
3    B   Red    340
4    C  Blue     70
5    C   Red    930 

Expectation:

I want to have a histogram like this:

1) x is 'Type' and y is 'Count'

2) 'Red' and 'Blue' in one combined bar for each type 

3) 'Blue' is on top of 'Red', with different colors.

I have tried:

df.plot.bar(x='Type', y='Count', rot=0)

But in this way 'Red' and 'Blue' are in separate bars, with same color.

enter image description here

This is not what I expect.

Any guidance is appreciated

CodePudding user response:

IIUC, you want:

>>> df.pivot("Type","Color","Count")[["Red", "Blue"]].plot.bar(stacked=True, color=["red", "blue"], legend=False, width=1)

enter image description here]

  • Related