Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
298 views
in Technique[技术] by (71.8m points)

python - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...