【问题标题】:How to display Summary statistics next to a plot using matplotlib or seaborn?如何使用 matplotlib 或 seaborn 在绘图旁边显示摘要统计信息?
【发布时间】:2019-09-25 12:03:42
【问题描述】:

我正在尝试创建一个函数,该函数将遍历数据框中的数字特征列表,以在其旁边显示直方图和汇总统计信息。我正在使用plt.figtext() 显示统计信息,但出现错误

num_features=[n1,n2,n3]

for i in num_features:
    fig, ax = plt.subplots()
    plt.hist(df[i])
    plt.figtext(1,0.5,df[i].describe() )
    ax.set_title(i)
    plt.show()

当我这样做时,我会收到一条错误/警告消息:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()

如果使用 df[n].mean() 而不是 describe() 效果很好

我做错了什么?有没有更好的方法来打印绘图并在其旁边显示一些统计数据?

【问题讨论】:

  • df[n].describe() 返回一个数据框,而df[n].mean() 返回一个数字。 plt.figtext 采用浮点数,而不是数据帧。您可能必须单独添加每个统计信息,而不使用describe()。不过这应该不会太难:)
  • 我就是这么想的。我会试一试的。谢谢。

标签: pandas matplotlib seaborn


【解决方案1】:

如上面的解决方案所示,文本格式有点混乱。为了解决这个问题,我添加了一个解决方法,我们将描述分成两个数字,然后对齐。

帮手:

def describe_helper(series):
    splits = str(series.describe()).split()
    keys, values = "", ""
    for i in range(0, len(splits), 2):
        keys += "{:8}\n".format(splits[i])
        values += "{:>8}\n".format(splits[i+1])
    return keys, values

现在绘制图表:

demo = np.random.uniform(0,10,100)
plt.hist(demo, bins=10)
plt.figtext(.95, .49, describe_helper(pd.Series(demo))[0], {'multialignment':'left'})
plt.figtext(1.05, .49, describe_helper(pd.Series(demo))[1], {'multialignment':'right'})
plt.show()

如果你在保存图片的时候也想保存figtext,改变bbox_inches:

plt.savefig('fig.png', bbox_inches='tight')

【讨论】:

    【解决方案2】:

    根据反馈添加了此功能,现在可以正常使用。

    for i in num_cols:
    #calculate number of bins first based on Freedman-Diaconis rule
        n_counts=df[i].value_counts().sum()
        iqr=df[i].quantile(0.75)-df[i].quantile(0.25)
        h = 2 * iqr * (n_counts**(-2/3))
        n_bins=(df[i].max()-df[i].min()).round(0).astype(np.int64)
    
        fig, ax = plt.subplots()
        plt.hist(df[i],bins=15)
        plt.figtext(1,0.5,s=t[i].describe().to_string())
        plt.show()
    

    【讨论】:

      【解决方案3】:

      您可以通过使用to_string() 将describe() 返回的数据帧格式化为字符串来“简化”您的代码:

      df = pd.DataFrame(np.random.normal(size=(2000,)))
      fig, ax = plt.subplots()
      ax.hist(df[0])
      plt.figtext(0.1,0.5, df.describe().to_string())
      plt.figtext(0.75,0.5, df.describe().loc[['mean','std']].to_string())
      

      【讨论】:

      • 谢谢..这就是我要找的
      猜你喜欢
      • 2021-11-05
      • 1970-01-01
      • 1970-01-01
      • 2019-10-21
      • 2018-11-23
      • 2015-01-04
      • 1970-01-01
      • 1970-01-01
      • 2015-11-05
      相关资源
      最近更新 更多