'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



Solution 1:[1]

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

Solution 2:[2]

This is how you can make a unstacked bar chart.

df_plot = df.groupby(["colomn", "colomn2"]).colomn2.count()
    
    
#create bar plot by group
df_plot.plot(kind='bar', color=[ 'r', 'b'])

(note: all the colomns need to be filled)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Ruben Visser