您可以将四分位间距绘制为 seaborn 线图上的误差带吗?

Can you plot interquartile range as the error band on a seaborn lineplot?

我正在使用 seaborn lineplot (https://seaborn.pydata.org/generated/seaborn.lineplot.html) 绘制时间序列数据,并绘制中位数而不是均值。示例代码:

import seaborn as sns; sns.set()
import matplotlib.pyplot as plt

fmri = sns.load_dataset("fmri")
ax = sns.lineplot(x="timepoint", y="signal", estimator = np.median, data=fmri)

我希望误差带显示四分位距而不是置信区间。我知道我可以使用 ci = "sd" 作为标准偏差,但是有没有一种简单的方法来添加 IQR?我想不通。

谢谢!

我不知道这是否可以单独使用 seaborn 完成,但这是使用 matplotlib 完成的一种方法,保持 seaborn 风格。 describe() 方法方便地提供 DataFrame 的汇总统计信息,其中包括四分位数,我们可以使用它来绘制具有四分位数间距的中位数。

import seaborn as sns; sns.set()
import matplotlib.pyplot as plt

fmri = sns.load_dataset("fmri")
fmri_stats = fmri.groupby(['timepoint']).describe()

x = fmri_stats.index
medians = fmri_stats[('signal', '50%')]
medians.name = 'signal'
quartiles1 = fmri_stats[('signal', '25%')]
quartiles3 = fmri_stats[('signal', '75%')]

ax = sns.lineplot(x, medians) 
ax.fill_between(x, quartiles1, quartiles3, alpha=0.3); 

您可以像您一样计算线图中的中位数,将 ci 设置为 none 并使用 ax.fill_between()

填写
import numpy as np
import seaborn as sns; sns.set()
import matplotlib.pyplot as plt

fmri = sns.load_dataset("fmri")
ax = sns.lineplot(x="timepoint", y="signal", estimator = np.median, 
                  data=fmri,ci=None)

bounds = fmri.groupby('timepoint')['signal'].quantile((0.25,0.75)).unstack()
ax.fill_between(x=bounds.index,y1=bounds.iloc[:,0],y2=bounds.iloc[:,1],alpha=0.1)