【问题标题】:Stacked bar plot in different colors in PandasPandas 中不同颜色的堆积条形图
【发布时间】:2019-12-08 18:35:57
【问题描述】:

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

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) 我提供了一个代码,它会生成两个堆叠的条形图。我希望第一个条形图(“男性”)使用颜色图 GnBU 着色,第二个条形图(“女性”)使用 RdPu。
  • 2) 另外,我想在图中添加更多这样的条形对(我提供了另一个数据集)。每对之间应该有很少的空白空间,因此可以识别哪两个条属于一起。很抱歉造成混乱,希望现在清楚了...

标签: python pandas plot colormap


【解决方案1】:

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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-03
    • 2021-12-02
    • 1970-01-01
    • 2017-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-16
    相关资源
    最近更新 更多