Python中seaborn tsplot函数中的标准差和误差条

2024-04-29 05:03:17 发布

您现在位置:Python中文网/ 问答频道 /正文

Seaborn如何计算误差条?示例:

import numpy as np; np.random.seed(22)
import seaborn as sns; sns.set(color_codes=True)
x = np.linspace(0, 15, 31)
data = np.sin(x) + np.random.rand(10, 31) + np.random.randn(10, 1)
ax = sns.tsplot(data=data, err_style="ci_bars")
plt.show()

如何计算ci_条(或ci_带)?

此外,在误差条或误差带与每个时间点的值的标准偏差相对应的地方,是否可以用ciúbar样式绘制tsplot图?(非标准平均误差或引导误差)


Tags: importnumpyci示例dataasnprandom
2条回答

Seaborn v0.8.0(2017年7月)中,增加了使用误差条显示标准偏差的能力,而不是通过设置ci=“sd”在大多数统计函数中引导置信区间。所以这个现在有效了

sns.tsplot(data=data, ci="sd") 

对于以前的Seaborn版本,绘制标准偏差的解决方法是在Seaborn tsplot的顶部使用matplotlib错误栏:

import numpy as np;
import seaborn as sns;
import pandas as pd
import matplotlib.pyplot as plt

# create a group of time series
num_samples = 90
group_size = 10
x = np.linspace(0, 10, num_samples)
group = np.sin(x) + np.linspace(0, 2, num_samples) + np.random.rand(group_size, num_samples) + np.random.randn(group_size, 1)
df = pd.DataFrame(group.T, index=range(0,num_samples))

# plot time series with seaborn
ax = sns.tsplot(data=df.T.values) #, err_style="unit_traces")

# Add std deviation bars to the previous plot
mean = df.mean(axis=1)
std  = df.std(axis=1)
ax.errorbar(df.index, mean, yerr=std, fmt='-o') #fmt=None to plot bars only

plt.show()

enter image description here

由于tsplot函数不提供直接设置错误条值或更改用于计算错误条值的方法的方法,因此我找到的唯一解决方案是对timeseries模块进行猴子修补:

import seaborn.timeseries

def _plot_std_bars(*args, central_data=None, ci=None, data=None, **kwargs):
    std = data.std(axis=0)
    ci = np.asarray((central_data - std, central_data + std))
    kwargs.update({"central_data": central_data, "ci": ci, "data": data})
    seaborn.timeseries._plot_ci_bars(*args, **kwargs)

def _plot_std_band(*args, central_data=None, ci=None, data=None, **kwargs):
    std = data.std(axis=0)
    ci = np.asarray((central_data - std, central_data + std))
    kwargs.update({"central_data": central_data, "ci": ci, "data": data})
    seaborn.timeseries._plot_ci_band(*args, **kwargs)

seaborn.timeseries._plot_std_bars = _plot_std_bars
seaborn.timeseries._plot_std_band = _plot_std_band

然后,用标准偏差误差条绘制

ax = sns.tsplot(data, err_style="std_bars", n_boot=0)

或者

ax = sns.tsplot(data, err_style="std_band", n_boot=0)

用标准偏差带绘图。

编辑:受this answer的启发,另一种(可能更明智的)方法是使用以下方法而不是tsplot

import pandas as pd
import seaborn as sns

df = pd.DataFrame.from_dict({
    "mean": data.mean(axis=0),
    "std": data.std(axis=0)
}).reset_index()

g = sns.FacetGrid(df, size=6)
ax = g.map(plt.errorbar, "index", "mean", "std")
ax.set(xlabel="", ylabel="")

Edit2:因为您询问tsplot如何计算其置信区间:它在每个时间点使用bootstrapping to estimate the distribution of the mean value,然后从这些分布中找到低百分位和高百分位值(对应于所使用的置信区间)。默认置信区间为68%——假设正态分布,相当于平均值的±1个标准差。分别为16%和84%。可以通过ci关键字参数更改置信区间。

相关问题 更多 >