在 matplotlib Python 中设置不同的条形颜色

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

Setting Different Bar color in matplotlib Python

pythonmatplotlibpandasbar-chart

提问by Santiago Munez

Supposely, I have the bar chart as below:

假设,我有如下条形图:

BarPlot

条形图

Any ideas on how to set different colors for each carrier? As for example, AK would be Red, GA would be Green, etc?

关于如何为每个运营商设置不同颜色的任何想法?例如,AK 是红色,GA 是绿色,等等?

I am using Pandas and matplotlib in Python

我在 Python 中使用 Pandas 和 matplotlib

>>> f=plt.figure()
>>> ax=f.add_subplot(1,1,1)
>>> ax.bar([1,2,3,4], [1,2,3,4])
<Container object of 4 artists>
>>> ax.get_children()
[<matplotlib.axis.XAxis object at 0x6529850>, <matplotlib.axis.YAxis object at 0x78460d0>,  <matplotlib.patches.Rectangle object at 0x733cc50>, <matplotlib.patches.Rectangle object at 0x733cdd0>, <matplotlib.patches.Rectangle object at 0x777f290>, <matplotlib.patches.Rectangle object at 0x777f710>, <matplotlib.text.Text object at 0x7836450>, <matplotlib.patches.Rectangle object at 0x7836390>, <matplotlib.spines.Spine object at 0x6529950>, <matplotlib.spines.Spine object at 0x69aef50>, <matplotlib.spines.Spine object at 0x69ae310>, <matplotlib.spines.Spine object at 0x69aea50>]
>>> ax.get_children()[2].set_color('r') #You can also try to locate the first patches.Rectangle object instead of direct calling the index.

For the suggestions above, how do exactly we could enumerate ax.get_children() and check if the object type is rectangle? So if the object is rectangle, we would assign different random color?

对于上面的建议,我们究竟如何枚举 ax.get_children() 并检查对象类型是否为矩形?那么如果对象是矩形,我们会分配不同的随机颜色吗?

采纳答案by CT Zhu

Simple, just use .set_color

简单,只要使用 .set_color

>>> barlist=plt.bar([1,2,3,4], [1,2,3,4])
>>> barlist[0].set_color('r')
>>> plt.show()

enter image description here

在此处输入图片说明

For your new question, not much harder either, just need to find the bar from your axis, an example:

对于你的新问题,也不难,只需要从你的轴上找到条形,一个例子:

>>> f=plt.figure()
>>> ax=f.add_subplot(1,1,1)
>>> ax.bar([1,2,3,4], [1,2,3,4])
<Container object of 4 artists>
>>> ax.get_children()
[<matplotlib.axis.XAxis object at 0x6529850>, 
 <matplotlib.axis.YAxis object at 0x78460d0>,  
 <matplotlib.patches.Rectangle object at 0x733cc50>, 
 <matplotlib.patches.Rectangle object at 0x733cdd0>, 
 <matplotlib.patches.Rectangle object at 0x777f290>, 
 <matplotlib.patches.Rectangle object at 0x777f710>, 
 <matplotlib.text.Text object at 0x7836450>, 
 <matplotlib.patches.Rectangle object at 0x7836390>, 
 <matplotlib.spines.Spine object at 0x6529950>, 
 <matplotlib.spines.Spine object at 0x69aef50>,
 <matplotlib.spines.Spine object at 0x69ae310>, 
 <matplotlib.spines.Spine object at 0x69aea50>]
>>> ax.get_children()[2].set_color('r') 
 #You can also try to locate the first patches.Rectangle object 
 #instead of direct calling the index.

If you have a complex plot and want to identify the bars first, add those:

如果您有一个复杂的图并想先识别条形,请添加:

>>> import matplotlib
>>> childrenLS=ax.get_children()
>>> barlist=filter(lambda x: isinstance(x, matplotlib.patches.Rectangle), childrenLS)
[<matplotlib.patches.Rectangle object at 0x3103650>, 
 <matplotlib.patches.Rectangle object at 0x3103810>, 
 <matplotlib.patches.Rectangle object at 0x3129850>, 
 <matplotlib.patches.Rectangle object at 0x3129cd0>, 
 <matplotlib.patches.Rectangle object at 0x3112ad0>]

回答by 7stud

I assume you are using Series.plot() to plot your data. If you look at the docs for Series.plot() here:

我假设您正在使用 Series.plot() 来绘制您的数据。如果您在此处查看 Series.plot() 的文档:

http://pandas.pydata.org/pandas-docs/dev/generated/pandas.Series.plot.html

http://pandas.pydata.org/pandas-docs/dev/generated/pandas.Series.plot.html

there is no colorparameter listed where you might be able to set the colors for your bar graph.

没有列出颜色参数,您可以在其中设置条形图的颜色。

However, the Series.plot() docs state the following at the end of the parameter list:

但是, Series.plot() 文档在参数列表的末尾声明了以下内容:

kwds : keywords
Options to pass to matplotlib plotting method

What that means is that when you specify the kindargument for Series.plot() as bar, Series.plot() will actually call matplotlib.pyplot.bar(), and matplotlib.pyplot.bar() will be sent all the extra keyword arguments that you specify at the end of the argument list for Series.plot().

这意味着当您将Series.plot()的kind参数指定为bar 时,Series.plot() 实际上会调用 matplotlib.pyplot.bar(),并且 matplotlib.pyplot.bar() 将发送所有额外的您在 Series.plot() 的参数列表末尾指定的关键字参数。

If you examine the docs for the matplotlib.pyplot.bar() method here:

如果您在此处查看 matplotlib.pyplot.bar() 方法的文档:

http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.bar

http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.bar

..it also accepts keyword arguments at the end of it's parameter list, and if you peruse the list of recognized parameter names, one of them is color, which can be a sequence specifying the different colors for your bar graph.

..它还在其参数列表的末尾接受关键字参数,如果您仔细阅读已识别参数名称的列表,其中之一是color,它可以是为条形图指定不同颜色的序列。

Putting it all together, if you specify the colorkeyword argument at the end of your Series.plot() argument list, the keyword argument will be relayed to the matplotlib.pyplot.bar() method. Here is the proof:

总而言之,如果您在 Series.plot() 参数列表的末尾指定color关键字参数,则关键字参数将被转发到 matplotlib.pyplot.bar() 方法。这是证据:

import pandas as pd
import matplotlib.pyplot as plt

s = pd.Series(
    [5, 4, 4, 1, 12],
    index = ["AK", "AX", "GA", "SQ", "WN"]
)

#Set descriptions:
plt.title("Total Delay Incident Caused by Carrier")
plt.ylabel('Delay Incident')
plt.xlabel('Carrier')

#Set tick colors:
ax = plt.gca()
ax.tick_params(axis='x', colors='blue')
ax.tick_params(axis='y', colors='red')

#Plot the data:
my_colors = 'rgbkymc'  #red, green, blue, black, etc.

pd.Series.plot(
    s, 
    kind='bar', 
    color=my_colors,
)

plt.show()


enter image description here

在此处输入图片说明

Note that if there are more bars than colors in your sequence, the colors will repeat.

请注意,如果序列中的条数多于颜色,则颜色会重复。

回答by Yannis P.

Update pandas 0.17.0

更新熊猫 0.17.0

@7stud's answer for the newest pandas version would require to just call

@7stud 对最新熊猫版本的回答只需要打电话

s.plot( 
    kind='bar', 
    color=my_colors,
)

instead of

代替

pd.Series.plot(
    s, 
    kind='bar', 
    color=my_colors,
)

The plotting functions have become members of the Series, DataFrame objects and in fact calling pd.Series.plotwith a colorargument gives an error

绘图函数已成为 Series、DataFrame 对象的成员,实际上pd.Series.plot使用color参数调用会产生错误