custom colors in matplotlib

Viewed 25

Hi I have two columns in my dataframe gender, countries

I am trying to get a bar graph of population of countries, for example: India - Male - 40 - Female-20 US - Male - 20 - Female-15 .....

I want to give custom color to male and female for example "Blue" for men and "pink" for female, How do I specify color here?

Below is my code:

a = df["Gender"]
b = a.groupby(df["Countries"]).value_counts()

b.unstack().plot.bar()

plt.xlabel("Countries")
plt.ylabel("Count of People")
plt.title("Count of genders based on their age Countries")
plt.show()
1 Answers

Use the color parameter, for example like this:

import pandas as pd
import seaborn as sns #To load some data

df = sns.load_dataset('iris')
df2 = df['species'].groupby(df['species']).value_counts().unstack()

#df2.columns
#Out[29]: Index(['setosa', 'versicolor', 'virginica'], dtype='object', name='species')

colors = {column:color for column, color in zip(df2.columns, ['green', 'cyan','blue'])} #Named colors: https://matplotlib.org/stable/gallery/color/named_colors.html

df2.plot.bar(color=colors)

enter image description here

Related