在Pandas的不同颜色的堆积条形图

时间:2017-10-13 11:09:55

标签: python pandas plot colormap

我对代码有两个问题(见下文)。

1)我有两个酒吧,我希望每个酒吧两个都用不同的色彩图着色(GnBu用于'男性'和RdPu用于'女性')。我尝试创建一个列表'颜色'包括两个色图,但它并没有很好地工作。

import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame(([[3.31, 3.19, 10.17, 7.69, 8.00, 20.83, 16.25, 30.00, 10.00, 38.00], [3.34, 5.13, 5.21, 4.56, 8.94, 7.75, 3.82, 1.75, 0, 0]]), columns=['18-24','25-29','30-34','35-39','40-44','45-49','50-54','55-59','60-64','65-70'], index=['male','female'])
color1 = plt.cm.GnBu(np.linspace(0, 1, 10))
color2 = plt.cm.RdPu(np.linspace(0, 1, 10))
colors=(color1,color2)
df.plot(kind='bar', stacked=True, width = 0.99, figsize=(10, 42), color=colors, rot=0)
plt.ylabel('history (years)')

2)如果我有第二个,第三个......数据集,例如

df = pd.DataFrame(np.abs([[3.71,3.29,2.59,3.06,2.57,2.70,5.50,2.25,2.00,2.50], [2.59,2.50,2.38,2.19,3.20,3.00,2.25,7.00,0,0]]), columns=['18-24','25-29','30-34','35-39','40-44','45-49','50-54','55-59','60-64','65-70'], index=['male','female'])

我希望将它绘制在同一个图中,但是前两个条形图有一些空间......,会感激一下提示。酒吧应始终配对('男性'女性')。

1 个答案:

答案 0 :(得分:0)

Stacked Bar Color

尝试以下代码:-

N = 3
top_sector = (914,300, 200) ## No of Investment in top sectors for C1/C2/C3
second_sector = (770,200,100) ## No of Investment in 2nd highest sector for C1/C2/C3
third_sector = (282,100,50) ## No of Investment in 3rd highest sector for C1/C2/C3
# fourth_sector = (0,0,0)`enter code here`
# fifth_sector = (0,0,0)`enter code here`
ind = np.arange(N)`enter code here`
width = 0.35

p1 = plt.bar(ind,top_sector,width,color=['blue'])
p2 = plt.bar(ind,second_sector,width,color=['red'])
p3 = plt.bar(ind,third_sector,width,color=['green'])`enter code here`
# p4 = plt.bar(ind,top_sector,width,color=['yellow'])`enter code here`
# p5 = plt.bar(ind,top_sector,width,color=['purple'])

    plt.xlabel('Top 3 Countries for Investment')

plt.ylabel('No of Investment (Count)')
plt.title('No of Investment in top 3 sectors of top 3 countries')
plt.xticks(ind,('USA' , 'GBR', 'IND'))
plt.yticks(np.arange(0,1000,200))`enter code here`
plt.legend((p1[0],p2[0],p3[0],p4[0],p5[0]),('Others',' Health', 'Entertainment', 'Cleantech / Semiconductors','News,Searching/Msg'))
plt.show()