简体   繁体   English

从数据框创建分组的条形图

[英]Create grouped bar graph from dataframe

Sample DataFrame 样本数据框

                 continent  avg_count_country  avg_age
Male        0      Asia                 55        5
            1    Africa                 65       10
            2    Europe                 75        8
Female      0      Asia                 50        7
            1    Africa                 60       12
            2    Europe                 70        0
Transgender 0      Asia                 30        6
            1    Africa                 40       11
            2    America                80       10

For the grouped bar graph: 对于分组的条形图:

X axis will have Male , Female , Transgender X轴将具有MaleFemaleTransgender

Y axis will have total counts Y轴将具有总数

3 bars in each Male , Female and Transgender MaleFemaleTransgender各有3个酒吧

Male and Female will have 3 bars grouped - Asia , Africa , Europe 男性和女性将分为3个酒吧- AsiaAfricaEurope

Transgender will have 3 bars grouped -- Asia , Africa , America 跨性别者将分为3个酒吧- AsiaAfricaAmerica

4 unique colors or legends [Asia , Africa ,Europe , America] 4种独特的颜色或传说[亚洲,非洲,欧洲,美国]

I can do it manually like plotting every bar 我可以像绘制每个条形一样手动完成

bars1 = //manually giving values
bars2 = //manually giving values
......bars3, bars4

plt.bar(r1, bars1, color='#7f6d5f', width=barWidth, edgecolor='white', label='var1') 
and plotting each bar like this

But want to do it in more optimized way or dynamic way 但是想要以更优化的方式或动态的方式进行

You can reshape your dataframe and use pandas plot: 您可以重塑数据框并使用熊猫图:

df_out = df.reset_index(level=1, drop=True)\
           .set_index(['continent'], append=True)['avg_count_country']\
           .unstack()

df_out.plot.bar()

Output: 输出:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM