【问题标题】:Iteratively plot stacked histograms pandas/matplotlib迭代地绘制堆积直方图 pandas/matplotlib
【发布时间】:2017-07-08 13:11:30
【问题描述】:

我想遍历数据框的列,并为每列绘制一个堆叠直方图,以区分两组(其中死亡 = 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() of unsized object”。所有列都是 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

【问题讨论】:

    标签: python pandas matplotlib


    【解决方案1】:

    我想通了:

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

    【讨论】:

      猜你喜欢
      • 2018-11-26
      • 1970-01-01
      • 1970-01-01
      • 2016-05-24
      • 2018-03-10
      • 2014-02-28
      • 2019-09-27
      相关资源
      最近更新 更多