Python 熊猫绘制数据框条形图,按类别使用颜色
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18897261/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
pandas plot dataframe barplot with colors by category
提问by jonas
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?
我想在组上制作一个带有着色的条形图。我还想指定颜色。在我的原始数据集中,我有很多组。有人可以帮我解决这个问题吗?
采纳答案by Viktor Kerkez
Just pass a color parameter to the plot function with a list of colors:
只需将颜色参数传递给带有颜色列表的 plot 函数:
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:
如果要绘制value
as 条形并且还希望group
确定条形的颜色,请使用:
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.
而不是列表理解。