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

时间:2017-02-19 06:55:26

标签: python pandas matplotlib

我希望遍历数据框的列并绘制每个列的堆积直方图,以区分两组(其中死亡= 0对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()"。所有列都是int或float。有助于理解错误的原因。

for x in df1:
    for y in df2:
        plt.figure()
        plt.hist([x, y], bins=50, stacked=True, color=['b','r'])
        plt.title(df1.x.name)
        plt.show()
  

TypeError:未确定对象的len()

1 个答案:

答案 0 :(得分:0)

我明白了:

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();