Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pandas plot dataframe barplot with colors by category

I would like to use pandas to plot a barplot with diffrent colors for category in column.

Here is a simple example: (index is variable)

df:
         value   group
variable               
a             10      1
b              9      1
c              8      1
d              7      2
f              6      2
g              5      3
h              4      3

I would like to make a barplot with coloring on group. I would also like to specify the colors. In my original dataset I have many goups. Could someone help me with this?

like image 826
jonas Avatar asked Sep 19 '13 14:09

jonas


People also ask

How do you add color to a Barplot in Python?

You can change the color of bars in a barplot using color argument. RGB is a way of making colors. You have to to provide an amount of red, green, blue, and the transparency value to the color argument and it returns a color.


1 Answers

Just pass a color parameter to the plot function with a list of colors:

df['group'].plot(kind='bar', color=['r', 'g', 'b', 'r', 'g', 'b', 'r'])

If you want to plot the value as bars and you also want the group to determine the color of the bar, use:

colors = {1: 'r', 2: 'b', 3: 'g'}
df['value'].plot(kind='bar', color=[colors[i] for i in df['group']])

You can also use something like:

list(df['group'].map(colors))

Instead of the list comprehension.

like image 184
Viktor Kerkez Avatar answered Sep 22 '22 12:09

Viktor Kerkez