python - 如何用 Pandas 创建堆叠子图

标签 python pandas matplotlib

我想为我的数据创建堆叠子图。我想要按“类型”、“周”作为我的 x 轴的子图,以及要堆叠的“分数”。

np.random.seed(1234)
test = pd.DataFrame({'week':[1,1,1,1,1,1,2,2,2,2,2,2],
                     'score':np.random.uniform(0,1,12),
                    'type': [0,1,0,1,0,1,0,1,0,1,0,1],
                     'type2':[3,3,4,4,5,5,3,3,4,4,5,5]})

这就是我现在所拥有的,如果我添加一个参数“subplot = True”

test.groupby(['week','type','type2']).agg('sum').unstack(1).plot(kind='bar', subplots=True)

enter image description here

最佳答案

我认为 - 但我不确定 - 很难组合 stackedsubplots 选项。所以这是一个解决方案,我希望产生预期的输出,但可能会有所改进。

# Test data
np.random.seed(1234)
test = pd.DataFrame({'week':[1,1,1,1,1,1,2,2,2,2,2,2],
                     'score':np.random.uniform(0,1,12),
                    'type': [0,1,0,1,0,1,0,1,0,1,0,1],
                     'type2':[3,3,4,4,5,5,3,3,4,4,5,5]})
grouped = test.groupby(['type','week','type2']).agg('sum')

# Preparing plots
fig, axes = plt.subplots(nrows=2)

for group_name, group in grouped.groupby(level=0):
    group.index = group.index.droplevel(0)
    group = group.unstack(1)
    group.columns = group.columns.droplevel()
    group.plot(kind='bar', stacked=True, ax=axes[group_name], title='type: ' + str(group_name))

result

关于python - 如何用 Pandas 创建堆叠子图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32701606/

相关文章:

python - 使用scipy的Logistic增长曲线不太正确

python - 如何优化将Spark数据帧的每一行写为单独的文件

python - Tensorflow 1.6 从 estimator.predict() 获取预测输出

python - 避免 Pandas DataFrame 中 for 循环的有效方法

python - 从字典导入为多索引 pd.DataFrame

python - 如何为k最近邻分类创建置信度估计的颜色图

python - 试图在注释或文字中查找关键字的所有实例?

python - 在 for 循环中使用 pandas .append

python - 有条件地移动饼图中单个数据标签的位置

python - 使小值在 python 中的 matplotlib 颜色条上可见