pandas plot dataframe barplot with colors by category

南笙酒味 提交于 2019-12-18 11:27:02

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/18897261/pandas-plot-dataframe-barplot-with-colors-by-category

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!