pandas 来自熊猫数据框python的barh图中行的不同颜色
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37447056/
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
different colors for rows in barh chart from pandas dataframe python
提问by michAmir
I have the following pandas dataframe:
我有以下Pandas数据框:
a b
bob 23 25
john 13 21
paul 20 19
david 17 14
michael 14 24
neil 22 11
df.plot(kind='barh')
I used the pandas plot function. I want to make a barh chart with all the rows(names) having a different colors is there a way to do this?
我使用了Pandas绘图功能。我想制作一个 barh 图表,其中所有行(名称)都具有不同的颜色,有没有办法做到这一点?
回答by andrew
It appears that Pandas only supports using the colormapattribute, which applies the same map to each row in your chart, e.g.:
看来 Pandas 只支持使用colormap属性,它将相同的映射应用于图表中的每一行,例如:
df.plot(kind='barh', colormap='RdBu')
For your purposes, you need to use Matplotlib directly.
出于您的目的,您需要直接使用 Matplotlib。
import matplotlib.pyplot as plt
import pandas as pd
df = pd.DataFrame({'a':[23, 13, 20, 17, 14, 22],
'b':[25, 21, 19, 14, 23, 11]},
index=['bob', 'john', 'paul', 'david', 'michael', 'neil'])
a_vals = df.a
b_vals = df.b
ind = np.arange(df.shape[0])
width = 0.35
# Set the colors
colors = ['b', 'g', 'r', 'c', 'm', 'y', 'g']
def autolabel(bars):
# attach some text labels
for bar in bars:
width = bar.get_width()
ax.text(width*0.95, bar.get_y() + bar.get_height()/2,
'%d' % int(width),
ha='right', va='center')
# make the plots
fig, ax = plt.subplots()
a = ax.barh(ind, a_vals, width, color = colors) # plot a vals
b = ax.barh(ind + width, b_vals, width, color = colors, alpha=0.5) # plot b vals
ax.set_yticks(ind + width) # position axis ticks
ax.set_yticklabels(df.index) # set them to the names
ax.legend((a[0], b[0]), ['a', 'b'], loc='center right')
autolabel(a)
autolabel(b)
plt.show()
Please refer to the following examples:
请参考以下例子:
1 - matplotlib 条形图
2- changing individual colors on bar chart
2- 改变条形图上的个别颜色