简体   繁体   English

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

[英]Iteratively plot stacked histograms pandas/matplotlib

I'd like to iterate through the columns of a dataframe and plot a stacked histogram for each column that distinguishes between two groups (where death = 0 vs 1). 我想遍历数据框的列并绘制每个列的堆积直方图,以区分两组(死亡= 0对1)。 How do I convert this code to something iterative? 如何将此代码转换为迭代的代码? (bun_max is one of the columns used as an example.) (Also, how do I get the legend to work?) (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 示例输出

This is what I have so far. 这就是我到目前为止所拥有的。 I get an error: "TypeError: len() of unsized object". 我收到一个错误:“未确定对象的TypeError:len()”。 All columns are either int or float. 所有列都是int或float。 Would be helpful to understand the reason for the error. 有助于理解错误的原因。

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() of unsized object TypeError:未确定对象的len()

I figured it out: 我想到了:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM