首页 > 解决方案 > 如何像在 ggplot 中一样在 matplotlib 中创建堆积条形直方图

问题描述

我正在尝试使用 matplotlib 中的堆积条来可视化 UCI 成人收入数据集中的年龄和收入。不幸的是,结果并不像我预期的那样。

在R中,代码是这样的

library(ggplot2)
ggplot(adult, aes(age)) + geom_histogram(aes(fill = income), color = "black",binwidth = 1)

结果是这样的

堆叠的

我正在使用这段代码:

plt.figure(figsize=(16, 8))
plt.hist(adult.age, bins=10, normed=None, histtype='bar', stacked=True)
plt.show()

你们能指出我错在哪里吗?

谢谢

标签: pythonpandasmatplotlibggplot2histogram

解决方案


IIUC,你想在 上分组,pd.cut然后是一个值计数:

# toy data
df = pd.DataFrame({'age':np.random.normal(50,15,1000),
                   'income':np.random.normal(5e4, 1e4, 1000)})

(df['income'].gt(5e4)
 .groupby(pd.cut(df.age, bins=range(20,80)))
 .value_counts()
 .unstack(-1)
 .plot.bar(stacked=True)
)

输出:

在此处输入图像描述


推荐阅读