python - 绘制堆积百分比条形图 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)。更多关于如何在图表中将每个条中的观察次数显示为文本的奖励积分。
解决方案
如果您的数据框是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)})
输出:
推荐阅读
- api - Postman API 删除功能问题
- python - 有任何用于识别简单形状的预制 .prototxt 和 .model 吗?
- python - 使用棉花糖进行 JSON 反序列化的嵌套类
- python - 计算时间序列中的峰值
- php - 使用 jquery / ajax / php 提交文件
- javascript - 使用 React 和 API 时如何修复“TypeError:items.map 不是函数”?
- sharepoint - 有没有办法,如何在 SharePoint Online 中将列更改为链接到项目?
- python - python从url和缩略图下载图像并调整大小
- amazon-ecs - 如何在不影响 ECS 服务的情况下捕获 on-JVM-exit 堆转储?
- javascript - 带有 this 保留字的 Javascript 箭头函数