【问题标题】:Error Bars with Seaborn and StripplotSeaborn 和 Stripplot 的误差线
【发布时间】:2017-08-26 20:06:41
【问题描述】:

我在使用 Seaborn 在 Python 中创建的绘图中添加误差线时遇到了一些困难。

我目前有一个“csv”格式的数据框;

TSMdatabase = 'TSMvsRunmaster.csv';
tsmdf = pd.read_csv(TSMdatabase, sep=',');

Dataframe 的标题格式如下:

Run,TSMX_Value,TSMX_Error,TSMX+1_Value,TSMX+1_Error,Source

然后我使用 for 循环读取不同的 TSM 值:

TSM = ['001', '002', '003', '004', '010', '011', '012', 
   '013', '016', '017', '101', '102', '104', '105', '106']

for x in TSM:
     tsm = x

最后我打算给我:

plt.figure()
sns.set_style("darkgrid")
ax = sns.stripplot(x="Run", y='TSM'+str(tsm)+'_Value', hue="Source", data=tsmdf, 
                   jitter=True, palette="Set2", split=True)
plt.xticks(rotation=40)
plt.title('Run TSM'+str(tsm)+' Comparison')
plt.show()

绘制某些没有误差线的 TSM

如果我再尝试添加误差线,我最终会在每个子数据集的中间只有一个误差线:

每个源,Python 和 Matlab 实际上在数据框中都有自己的错误!

有人有什么想法吗!真的非常感谢!

【问题讨论】:

  • 首先,您需要包括如何将误差线添加到绘图中,'然后我尝试添加误差线' 可能意味着任何事情。其次,使用minimal reproducible example 会大大增加您获得帮助的机会。因此,如果可以使用一些模型数据来重现该行为,请提供相应的代码。

标签: python matplotlib plot seaborn


【解决方案1】:

绘制均值+误差更适合sns.pointplot(),而不是sns.stripplot()。这在 Seaborn 文档中有所说明:

sns.pointplot 使用散点图字形显示点估计值和置信区间。点图表示通过散点图点的位置对数值变量的集中趋势的估计,并使用误差线提供该估计周围的不确定性的一些指示。

sns.stripplot 绘制一个散点图,其中一个变量是分类变量。条形图可以单独绘制,但如果您想要显示所有观察结果以及基本分布的一些表示,它也是箱形图或小提琴图的一个很好的补充。

如果您可以访问所有观察结果,而不仅仅是均值 + 误差,那么您可以通过以下方式实现您想要的:

import seaborn as sns
%matplotlib inline

tips = sns.load_dataset('tips')
sns.pointplot('sex', 'tip', hue='smoker',
    data=tips, dodge=True, join=False)

您可以使用 ci 参数从默认的 95% 更改置信区间的类型:

sns.pointplot('sex', 'tip', hue='smoker',
    data=tips, dodge=True, join=False, ci='sd')

在上面,Seaborn 计算了误差和集中趋势的测量值。如果您已经预先计算了这些,那就有点棘手了,因为目前无法将sns.pointplot() 与预先计算的错误栏一起使用。在使用sns.pointplot() 绘制均值后,我使用plt.errorbar() 添加错误:

ax = sns.pointplot('sex', 'tip', hue='smoker',
    data=tips, dodge=True, join=False, ci=None)

# Find the x,y coordinates for each point
x_coords = []
y_coords = []
for point_pair in ax.collections:
    for x, y in point_pair.get_offsets():
        x_coords.append(x)
        y_coords.append(y)

# Calculate the type of error to plot as the error bars
# Make sure the order is the same as the points were looped over
errors = tips.groupby(['smoker', 'sex']).std()['tip']
colors = ['steelblue']*2 + ['coral']*2
ax.errorbar(x_coords, y_coords, yerr=errors,
    ecolor=colors, fmt=' ', zorder=-1)

你也可以直接使用 matplotlib 来绘制整个图,如果你手动提供 x 位置,类似于this example

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-03
    • 1970-01-01
    • 2021-08-01
    • 2021-05-01
    • 2021-02-23
    • 2019-08-01
    • 1970-01-01
    相关资源
    最近更新 更多