如何在Seaborn Lineplot中使用自定义错误栏? [英] How to use custom error bar in seaborn lineplot?

查看:41
本文介绍了如何在Seaborn Lineplot中使用自定义错误栏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 seaborn.lineplot 生成一些时间序列图.我已经在两个列表中预先计算了一种特定类型的误差线,例如, upper = [1,2,3,4,5] lower = [0,1,2,3,4] .有没有办法在这里自定义错误栏,而不是在 lineplot 中使用CI或Std错误栏?

解决方案

如果您想要除 seaborn.lineplot 提供的错误带/条以外的其他错误带/条,则必须自己绘制它们.这是几个示例,说明如何在matplotlib中绘制误差带和误差线并获得与seaborn中的图相似的图.它们是使用作为熊猫数据框导入的 fmri 示例数据集构建的,并且基于

现在让我们说,我希望有一个误差带,它覆盖均值每一侧每个时间点的测量标准偏差的一半.由于无法在调用 lineplot 函数时设置此首选项,因此,据我所知,最简单的解决方案是使用matplotlib从头开始创建图.

 #具有自定义误差带的Matplotlib图#定义要绘制的变量y_mean = df.groupby('timepoint').mean()['signal']x = y_mean.index#使用选定的不确定性度量来计算上下限:此处#这是每次测量的标准偏差的一小部分#时间点基于无偏样本方差y_std = df.groupby('timepoint').std()['signal']错误= 0.5 * y_std较低= y_mean-错误上限= y_mean +错误#绘制带有误差带和额外格式的绘图以匹配原始样式无花果,ax = plt.subplots(figsize =(9,5))ax.plot(x,y_mean,label ='信号平均值')ax.plot(x,较低,color ='tab:blue',alpha = 0.1)ax.plot(x,上部,color ='tab:blue',alpha = 0.1)ax.fill_between(x,较低,较高,alpha = 0.2)ax.set_xlabel('timepoint')ax.set_ylabel('signal')ax.spines ['top'].set_visible(False)ax.spines ['right'].set_visible(False)plt.show() 

如果您希望使用误差线,那么这就是seaborn线图的样子:

 #根据标准偏差绘制带有误差线的sealine线图无花果,ax = plt.subplots(figsize =(9,5))sns.lineplot(data = df,x ="timepoint",y ="signal",ci ='sd',err_style ='bars')sns.despine()plt.show() 

这里是如何使用自定义错误栏使用matplotlib获取相同类型的图:

 #具有自定义错误栏的Matplotlib图#如果出于某种原因,您只有上下限的列表#而不是每个点的错误列表,此函数可以#派上用场:#错误= sns.utils.ci_to_errsize((下部,上部),y_mean)#使用误差线和额外的格式绘制绘图以匹配原始样式无花果,ax = plt.subplots(figsize =(9,5))ax.errorbar(x,y_mean,错误,color ='tab:blue',ecolor ='tab:blue')ax.set_xlabel('timepoint')ax.set_ylabel('signal')ax.spines ['top'].set_visible(False)ax.spines ['right'].set_visible(False)plt.show()#注意:在此示例中,y_mean和error存储为pandas系列#因此,可以使用此pandas绘图功能获得相同的绘图:#y_mean.plot(yerr =错误) 

Matplotlib文档: fill_between 错误栏

I am using seaborn.lineplot to generate some time series plots. I have pre-compute a specific kind of error bars in two lists, e.g., upper=[1,2,3,4,5] lower=[0,1,2,3,4]. Is there a way I could customize the error bar here, instead of using the CI or Std error bars in lineplot?

解决方案

If you want error bands/bars other than the ones that seaborn.lineplot offers, you have to plot them yourself. Here are a couple examples of how to draw an error band and error bars in matplotlib and get plots that look similar to those in seaborn. They are built with the fmri sample dataset imported as a pandas dataframe and are based on one of the examples shown in the seaborn documentation on the lineplot function.

import numpy as np                 # v 1.19.2
import pandas as pd                # v 1.1.3
import matplotlib.pyplot as plt    # v 3.3.2
import seaborn as sns              # v 0.11.0

# Import dataset as a pandas dataframe
df = sns.load_dataset('fmri')

This dataset contains a time variable called timepoint with 56 measurements of a signal at each of the 19 time points. I use the default estimator which is the mean. And to keep things simple, instead of using the confidence interval of the standard error of the mean as the measure of uncertainty (aka error), I use the standard deviation of the measurements at each time point. This is set in lineplot by passing ci='sd', the error extends to one standard deviation on each side of the mean (i.e. is symmetric). Here is what the seaborn lineplot looks like with an error band (by default):

# Draw seaborn lineplot with error band based on the standard deviation
fig, ax = plt.subplots(figsize=(9,5))
sns.lineplot(data=df, x="timepoint", y="signal", ci='sd')
sns.despine()
plt.show()

Now let's say I would prefer to have instead an error band that spans half a standard deviation of the measurements at each time point on each side of the mean. As it is not possible to set this preference when calling the lineplot function, the easiest solution to my knowledge is to create the plot from scratch using matplotlib.

# Matplotlib plot with custom error band

# Define variables to plot
y_mean = df.groupby('timepoint').mean()['signal']
x = y_mean.index

# Compute upper and lower bounds using chosen uncertainty measure: here
# it is a fraction of the standard deviation of measurements at each
# time point based on the unbiased sample variance
y_std = df.groupby('timepoint').std()['signal']
error = 0.5*y_std
lower = y_mean - error
upper = y_mean + error

# Draw plot with error band and extra formatting to match seaborn style
fig, ax = plt.subplots(figsize=(9,5))
ax.plot(x, y_mean, label='signal mean')
ax.plot(x, lower, color='tab:blue', alpha=0.1)
ax.plot(x, upper, color='tab:blue', alpha=0.1)
ax.fill_between(x, lower, upper, alpha=0.2)
ax.set_xlabel('timepoint')
ax.set_ylabel('signal')
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
plt.show()

If you prefer to have error bars, this is what the seaborn lineplot looks like:

# Draw seaborn lineplot with error bars based on the standard deviation
fig, ax = plt.subplots(figsize=(9,5))
sns.lineplot(data=df, x="timepoint", y="signal", ci='sd', err_style='bars')
sns.despine()
plt.show()

Here is how to get the same type of plot with matplotlib using custom error bars:

# Matplotlib plot with custom error bars

# If for some reason you only have lists of the lower and upper bounds
# and not a list of the errors for each point, this seaborn function can
# come in handy:
# error = sns.utils.ci_to_errsize((lower, upper), y_mean)

# Draw plot with error bars and extra formatting to match seaborn style
fig, ax = plt.subplots(figsize=(9,5))
ax.errorbar(x, y_mean, error, color='tab:blue', ecolor='tab:blue')
ax.set_xlabel('timepoint')
ax.set_ylabel('signal')
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
plt.show()

# Note: in this example, y_mean and error are stored as pandas series
# so the same plot can be obtained using this pandas plotting function:
# y_mean.plot(yerr=error)

Matplotlib documentation: fill_between, specify error bars, subsample error bars

Pandas documentation: error bars

这篇关于如何在Seaborn Lineplot中使用自定义错误栏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆