如何使用Seaborn在条形图中显示平均值

时间:2020-11-11 03:53:39

标签: python pandas matplotlib seaborn

请使用表格中所述的简单数据输入来帮助绘制Seaborn条形图:

我已经有一个模板,我想对其进行修改以显示“平均值”以及不同的误差线,如下图所示。预先感谢您的帮助。

import os, shutil
    
source_folder = r'C:\Users\ABC\DEF\GHI'
target_folder = r'H:\all_pdf_files'

for root, subdirs, files in os.walk(source_folder):
    for file in files:
        if file.endswith('.pdf'):
            shutil.copyfile(os.path.join(root, file), os.path.join(target_folder, file))

2 个答案:

答案 0 :(得分:1)

Seaborn在使用长格式数据时功能最强大。因此,您可能需要转换数据,如下所示:

sns.barplot(data=data_df.melt('stages', value_name='Delay', var_name='Time'), 
            x='Time', y='Delay',
            capsize=0.1, edgecolor='k')

输出:

enter image description here

答案 1 :(得分:1)

  • 给出示例数据,对于seaborn.barplot带有错误条带上限的情况,data_df必须从宽格式转换为整齐(长)格式。
    • 同样重要的是要记住,条形图仅显示平均值(或其他估计量)
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

# test data
a,b,c,d = [],[],[],[]

for i in range(1,5):
    np.random.seed(i)
    a.append(np.random.uniform(35,55))
    b.append(np.random.uniform(40,70))
    c.append(np.random.uniform(63,85))
    d.append(np.random.uniform(59,80))

# dataframe
data_df =pd.DataFrame({'S1':a,'S2':b,'S3':c,'S4':d})

# convert the data_df to a tidy format
df = data_df.stack().reset_index(level=1).rename(columns={'level_1': 'set', 0: 'val'})

set        val
 S1  43.340440
 S2  61.609735
 S3  63.002516
 S4  65.348984
 S1  43.719898
 S2  40.777787
 S3  75.092575
 S4  68.141770
 S1  46.015958
 S2  61.244435
 S3  69.399904
 S4  69.727380
 S1  54.340597
 S2  56.416967
 S3  84.399056
 S4  74.011136

使用seaborn.barplot

  • estimator参数的默认值为mean,因此,条形的高度是该组的平均值。
  • 钢筋高度是用p.get_height中提取的,可用于注释钢筋。
fit, ax = plt.subplots(figsize=(8, 6))
sns.barplot(x='set', y='val', data=df, capsize=0.2, ax=ax)

# show the mean
for p in ax.patches:
    ax.annotate(f'mean:\n{p.get_height():0.2f}', (p.get_x() + p.get_width() / 2., p.get_height() / 2), ha='center', va='center', xytext=(0, 10), textcoords='offset points')

plt.xlabel('Delay')
plt.ylabel('Time')
plt.show()

enter image description here