【问题标题】:Setting Different Bar color in matplotlib Python [duplicate]在matplotlib Python中设置不同的条形颜色[重复]
【发布时间】:2013-09-29 04:26:08
【问题描述】:

假设我有如下条形图:

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

我在 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.

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

【问题讨论】:

  • my_colors = ['brown','pink', 'red', 'green', 'blue', 'cyan','orange','purple'] plt.bar(yourX,yourY ,color=my_colors)

标签: python matplotlib pandas bar-chart


【解决方案1】:

简单,只需使用.set_color

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

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

>>> 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.

如果您有一个复杂的情节并想首先识别条形,请添加这些:

>>> 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>]

【讨论】:

  • 感谢您的回复。但是,我从以下位置获取条形图: dfPlotSum.plot(kind="bar", title=titleStr, legend=False) 此函数将返回 ax 对象。关于如何以这种方式设置颜色的任何想法?谢谢!
  • 查看编辑,这是一个简单的绘图,所以我知道第一个柱的索引为 2。如果您正在处理一个复杂的绘图,您必须首先找到要更改的柱。不能更具体,因为我没有你的dfPlotSum.plot(),但想法是一样的。
  • 感谢您的补充回答。我如何准确地找到子对象是指条形图的矩形?是否有这样的可枚举函数可以检查对象的类型?例如,对于 ax.get_children() 中的 i 是矩形? python 中是否有类似 C# 中的 is 关键字?
  • 请注意,这会删除栏的黑色边框(边缘)。可以使用:barlist[0].set_edgecolor("black") 将其恢复。更好的方法可能是使用barlist[0].set_facecolor('r'),它不会改变条形的边缘。
  • 我尝试使用barlist=plt.bar(['a','b','c','d'], [1,2,3,4]) 绘制条形图,但使用barlist['a'].set_color('r') 失败。
【解决方案2】:

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

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

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

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

kwds : keywords
Options to pass to matplotlib plotting method

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

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

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

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

总而言之,如果您在 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()

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

【讨论】:

  • 我不得不在 pandas: 0.24.2, matplotlib: 3.1.0 中使用color = list('rgbkymc')
【解决方案3】:

更新熊猫 0.17.0

@7stud 对最新 pandas 版本的回答只需要调用

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

而不是

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

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

【讨论】:

  • 我不得不在 pandas: 0.24.2, matplotlib: 3.1.0 中使用color = list('rgbkymc')
猜你喜欢
  • 2014-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-07
  • 2018-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多