Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I change the color of a grouped bar plot in Pandas?

I have this plot that you'll agree is not very pretty. Other plots I made so far had some color and grouping to them out of the box.

I tried manually setting the color, but it stays black. What am I doing wrong? Ideally it'd also cluster the same tags together.

df.groupby(['tags_0', 'gender']).count().plot(kind='barh', legend=False, color=['r', 'g', 'b'])

enter image description here

like image 322
Pepijn Avatar asked Sep 15 '25 11:09

Pepijn


2 Answers

You need to unstack your results:

df.groupby(['tags_0', 'gender']).gender.count().unstack().plot(kind='barh', legend=False, color=['r', 'g', 'b'])

Chart

I don't have your data, so just used a value of one for each tag/gender combo.

like image 100
Alexander Avatar answered Sep 18 '25 08:09

Alexander


You need to flatten your data. Using unstack() is one way. Alternatively, you can use pivot_table(). Here is the code.

import pandas as pd

# try to simulate your data
characters = 'Tank Support Marksman Mage Figher Assassin'.split(' ')
random_weight = abs(np.random.randn(len(characters)))
random_weight = random_weight / random_weight.sum()
gender = 'male female'.split(' ')

index1 = np.random.choice(characters, size=1000, p=random_weight)
index2 = np.random.choice(gender, size=1000, p=[0.4, 0.6])
multi_index = pd.MultiIndex.from_tuples(list(zip(index1, index2)), names=['character', 'gender'])

data = pd.DataFrame(np.random.randn(1000), columns=['value'], index=multi_index)
data.reset_index(inplace=True)

# do your groupby
group_counts = data.groupby(['character', 'gender']).count().reset_index()
# do pivot table
table = pd.pivot_table(group_counts, index='gender', columns='character', values='value')
# set your own colors here
table.plot(kind='barh', color=['r', 'g', 'b', 'k', 'm', 'y'])

enter image description here

like image 44
Jianxun Li Avatar answered Sep 18 '25 08:09

Jianxun Li