可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
This question already has an answer here:
Supposely, I have the bar chart as below:

Any ideas on how to set different colors for each carrier? As for example, AK would be Red, GA would be Green, etc?
I am using Pandas and matplotlib in Python
>>> f=plt.figure() >>> ax=f.add_subplot(1,1,1) >>> ax.bar([1,2,3,4], [1,2,3,4]) >>> ax.get_children() [, , , , , , , , , , , ] >>> 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?
回答1:
Simple, just use .set_color
>>> barlist=plt.bar([1,2,3,4], [1,2,3,4]) >>> barlist[0].set_color('r') >>> plt.show()

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]) >>> ax.get_children() [, , , , , , , , , , , ] >>> 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) [, , , , ]
回答2:
I assume you are using Series.plot() to plot your data. If you look at the docs for Series.plot() here:
http://pandas.pydata.org/pandas-docs/dev/generated/pandas.Series.plot.html
there is no color parameter 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:
kwds : keywords Options to pass to matplotlib plotting method
What that means is that when you specify the kind argument 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().
If you examine the docs for the matplotlib.pyplot.bar() method here:
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.
Putting it all together, if you specify the color keyword 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:
import pandas as pd import matplotlib.pyplot as plt s = pd