首页 > 解决方案 > 绘制堆积百分比条形图 matplotlib

问题描述

假设我有以下包含两列的数据框:标签:可以是-1、0或1。years_of_expereicen:可以是0,1,2,3,4,5,6,7,8,9

label   SSP_years_of_experience
22640   -1.0    5.0
181487  1.0 3.0
327672  0.0 9.0
254919  0.0 6.0
136942  1.0 10.0

我的目标是使用这个数据框来创建一个百分比堆积条形图,其中 x 轴是经验年数,条形图是不同的颜色,每个颜色都包含一年的经验值。换句话说,我们在 x 轴上有 10 个可能的值,然后对应于每个标签的不同颜色值的三个条形图。y 轴应以百分比为单位。

我会知道如何在 R(使用 ggplot)中做到这一点,但我是 matplotlib 的新手,对 python 有点陌生。

我可以将两列作为变量传递的奖励点(例如x,y)。更多关于如何在图表中将每个条中的观察次数显示为文本的奖励积分。

标签: pythonpandasmatplotlib

解决方案


如果您的数据框是pandas,请尝试:

exp_name = 'year_of_experience'
label_name = 'label'
new_df = (df.groupby(exp_name)[label_name]
            .value_counts(normalize=True)
            .sort_index()
            .unstack()
         )

new_df.plot.bar(stacked=True)

玩具数据框:

np.random.seed(0)
df = pd.DataFrame({'label': np.random.choice([-1,0,1], size=1000, replace=True),
                   'year_of_experience': np.random.randint(0,10, 1000)})

输出:

在此处输入图像描述


推荐阅读