2017-02-19 55 views
1

我想遍历一个数据框的列并绘制每个列的区别两个组(其中死亡= 0与1)的堆积直方图。如何将此代码转换为迭代的内容? (bun_max是作为例子的一列。)(另外,我如何才能传说的工作?)迭代地绘制堆叠柱状图pandas/matplotlib

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() of unsized object

回答

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

将是很好,如果有人可以绘制此使用的次要情节... – ACL