2017-02-19 56 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