首页 > 解决方案 > SPSS风格的“集群”条形图,使用python和pandas在多列中计数

问题描述

我有一些分类数据

example_data = {'Role':['Teacher', 'Teacher', 'Student', 'Admin', 'Student'],
    'Preference': ['Online', 'Blended', 'Blended', 'Face-to-face', 'Face-to-face'],
    'Location' : ['City', 'City', 'City', 'Rural', 'Rural']} 
    
df = pd.DataFrame(example_data, columns=['Role','Preference','Location'])

我想制作一个“聚集”条形图,其中的计数df['Role']df['Preference']偏好位于 x 轴上,y 轴是每个偏好的计数,每个条形图按角色聚集。在 SPSS 中,这称为聚集条形图,看起来像

spss聚类条形图

现在这个例子显然来自假数据,我并不担心样式,但我尝试了各种排列,但我仍然遗漏了一些东西groupby()value_counts()

任何帮助将非常感激

标签: pythonpandascharts

解决方案


尝试这个:

pd.crosstab(df['Preference'], df['Role']).plot.bar()

输出:

在此处输入图像描述


推荐阅读