迭代绘制堆积直方图pandas/matplotlib

2024-09-30 18:34:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我想遍历一个数据帧的列,并为每个列绘制一个堆叠的直方图,以区分两个组(其中death=0 vs 1)。如何将这些代码转换为迭代的代码?(bun_max是其中一个用作示例的列。)(另外,如何使图例起作用?)在

df1 = temp[temp['death'] == 0]
df2 = temp[temp['death'] == 1]

plt.figure()
plt.hist([df1.bun_max, df2.bun_max], bins=50, stacked=True, color=['b','r']);
plt.title(df1.bun_max.name)
plt.ylabel('ICU admits')
plt.xlabel(df1.bun_max.name)
plt.legend()
plt.show()

Example output

这就是我目前所拥有的。我得到一个错误:“TypeError:len()of unsize object”。所有列都是int或float。有助于理解错误的原因。在

^{pr2}$

TypeError: len() of unsized object


Tags: of数据代码namelenobject错误plt
1条回答
网友
1楼 · 发布于 2024-09-30 18:34:13

我想出来了:

df1 = temp[temp['death'] == 0]
df2 = temp[temp['death'] == 1]
df1 = df1.drop('death', axis=1)
df2 = df2.drop('death', axis=1)

for col1 in df1.columns:
    for col2 in df2.columns:
        if col1 == col2:
            plt.figure();
            plt.hist([df1[col1], df2[col2]], bins=50, stacked=True, color=['b','r']);
            plt.title(df1[col1].name)
            plt.ylabel('ICU admits')
            plt.xlabel(df1[col1].name)
            plt.show();

相关问题 更多 >