pandas 按照类别按颜色绘制数据框条形图 [英] pandas plot dataframe barplot with colors by category
问题描述
我想使用pandas在列中为类别绘制具有不同颜色的条形图.
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?
推荐答案
只需将颜色参数和颜色列表传递给plot函数:
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'])
如果要将value
绘制为条形,并且还希望group
确定条形的颜色,请使用:
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))
而不是列表理解.
这篇关于 pandas 按照类别按颜色绘制数据框条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!