更改 Pandas 条形图的颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45967310/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 04:21:15  来源:igfitidea点击:

Change colours of Pandas bar chart

pandasmatplotlibplot

提问by user4896331

I want the bars in a Pandas chart to each be given a different colour. The solution looks pretty simple according to this postand ones like it.

我希望 Pandas 图表中的每个条形都有不同的颜色。根据这篇文章和类似文章,该解决方案看起来非常简单。

When I try to emulate the solution, I end up with all the bars the same colour (albeit a different colour from the standard one). I guess that I'm doing something wrong, but I can't see what it is. Anyone else see it?

当我尝试模拟解决方案时,我最终使所有条形的颜色相同(尽管颜色与标准条形不同)。我想我做错了什么,但我看不到它是什么。还有人看吗?

fig = df.plot(kind='bar',    # Plot a bar chart
            legend=False,    # Turn the Legend off
            width=0.75,      # Set bar width as 75% of space available
            figsize=(8,5.8),  # Set size of plot in inches
            colormap='Paired')

The colormap='Paired'is the bit that's meant to change the colours. I get this: enter image description here

colormap='Paired'是旨在改变颜色的位。我明白了: 在此处输入图片说明

It's nice, but all the bars are the same colour! I'm making other changes to the plot, as you can see above, but they're all formatting of text or removal of axis details.

这很好,但所有的酒吧都是一样的颜色!正如您在上面看到的,我正在对绘图进行其他更改,但它们都是文本格式或轴详细信息的删除。

回答by Scott Boston

Let's use this code instead:

让我们改用这段代码:

df.plot(kind='bar',    # Plot a bar chart
        legend=False,    # Turn the Legend off
        width=0.75,      # Set bar width as 75% of space available
        figsize=(8,5.8),  # Set size of plot in inches
        color=[plt.cm.Paired(np.arange(len(df)))])

enter image description here

在此处输入图片说明

回答by Bill

This should also work:*

这也应该有效:*

df['Degree'].plot.bar()

This is different because df['Degree']is a series.

这是不同的,因为df['Degree']是一个系列。

Pandas Series seem to be plotted with each bar a different colour (presumably as each is assumed to be from a different category or label) whereas in a dataframe each series is assumed to be a set of values from one category so they are given the same colour.

Pandas 系列似乎用不同的颜色绘制每个条形(大概是因为每个条形都被假定为来自不同的类别或标签),而在数据框中,每个系列都被假定为来自一个类别的一组值,因此它们被赋予相同的颜色。

For example:

例如:

s = pd.Series({'a': 100, 'b': 74, 'c': 50})
s.plot.bar()

Produces:

产生:

enter image description here

在此处输入图片说明

UPDATE:

更新:

* Apparently for pandas versions < 0.17.0 you must use s.plot(kind='bar')not s.plot.bar(). I suspect the colour behaviour I am showing here is also version-specific. This demo was done with version 0.22.0.

* 显然,对于低于 0.17.0 的 pandas 版本,您必须使用s.plot(kind='bar')not s.plot.bar()。我怀疑我在这里展示的颜色行为也是特定于版本的。这个演示是用 0.22.0 版本完成的。