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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With