pandas plot dataframe barplot with colors by category

前端 未结 1 1026
挽巷
挽巷 2020-12-14 03:04

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:
                  


        
相关标签:
1条回答
  • 2020-12-14 03:58

    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.

    0 讨论(0)
提交回复
热议问题