根据对每个条形图总数的贡献在条形图的条形图上添加颜色

时间:2020-09-20 12:14:56

标签: python matplotlib seaborn

下图是一个数据框,显示了从每个大陆到一个国家的移民。我该如何绘制一个条形图来显示每年的总和,并在每个条形图上通过对每个洲使用不同的颜色来显示每个洲的贡献?

到目前为止,我得到的代码如下:

df_continent = df_can.groupby('Continent').sum()
years = df_continent.columns.tolist() 

enter image description here

1 个答案:

答案 0 :(得分:3)

我没有您期望的明确输出示例,但是我敢肯定您会发现 第一个示例只是一张按洲堆积的年度移民人数图表。 第二个示例是每个大陆按年份组成图的示例。

import pandas as pd
import numpy as np
import io

data = '''
continent 1980 1981 1982 1983 1984
Africa 3951 4363 3819 2617 2639
Asiz 31025 34314 30214 24696 27274
Europe 39760 44802 42720 24638 22287
"Latin America" 13081 15215 16769 15427 13678
"Northern America" 9378 10030 9074 7100 6661
Oceania 1942 1839 1675 1018 878
'''

# df = pd.read_csv(io.StringIO(data), sep='\s+')
df = pd.read_csv(io.StringIO(data), delim_whitespace=True)
df.plot(x='continent', kind='bar', stacked=True)

enter image description here

百分比类型

d = df[df.columns[1:]].div(df[df.columns[1:]].sum())
df1 = pd.concat([df[['continent']],d],1)
df1.set_index('continent', inplace=True)
df1
            1980    1981    1982    1983    1984
continent                   
Africa  0.039854    0.039462    0.036626    0.034664    0.035945
Asiz    0.312951    0.310357    0.289764    0.327117    0.371494
Europe  0.401061    0.405217    0.409702    0.326348    0.303567
Latin America   0.131949    0.137614    0.160821    0.204342    0.186306
Northern America    0.094596    0.090718    0.087023    0.094045    0.090728
Oceania 0.019589    0.016633    0.016064    0.013484    0.011959

df1.T.plot(kind='bar', stacked=True)

enter image description here