假设,我有如下条形图:
关于如何为每个载体设置不同的颜色有什么想法吗?例如,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()并检查对象类型是否为矩形?所以如果对象是矩形,我们会分配不同的随机颜色?
简单,只要使用
.set_color
对于你的新问题,也不难,只需要从你的坐标轴上找到条,例如:
如果您有一个复杂的绘图,并且希望首先标识条形图,请添加以下内容:
更新pandas 0.17.0
@7stud对于最新的熊猫版本的回答只需要打电话
而不是
绘图函数已成为系列、数据帧对象的成员,而实际上用
color
参数调用pd.Series.plot
会产生错误我假设您使用Series.plot()来绘制数据。如果您在此处查看Series.plot()的文档:
http://pandas.pydata.org/pandas-docs/dev/generated/pandas.Series.plot.html
没有列出可以为条形图设置颜色的color参数。
但是,Series.plot()文档在参数列表的末尾声明如下:
这意味着,当您将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()参数列表的末尾指定colorkeyword参数,keyword参数将被中继到matplotlib.pyplot.bar()方法。这是证据:
请注意,如果序列中的条形图多于颜色,则颜色将重复。
相关问题 更多 >
编程相关推荐