Sea*_*123 9 python numpy matplotlib seaborn
我有一个带有均匀样本的时间序列保存到一个numpy数组,我想用自举置信区间绘制它们的平均值.通常情况下,我使用tsplotSeaborn来实现这一目标.但是,现在这已被弃用.我该怎么用替代品?
以下是根据Seaborn文档改编的示例用法:
x = np.linspace(0, 15, 31)
data = np.sin(x) + np.random.rand(10, 31) + np.random.randn(10, 1)
sns.tsplot(data)
Run Code Online (Sandbox Code Playgroud)
注意:这类似于" Seaborn tsplot错误 "和" 带有seaborn tsplot的多线图 "的问题.但是,在我的情况下,我实际上需要Seaborn的置信区间功能,因此不能简单地使用Matplotlib而不需要一些笨拙的编码.
Imp*_*est 12
tsplot可以使用matplotlib轻松复制问题中的示例.
import numpy as np; np.random.seed(1)
import matplotlib.pyplot as plt
import seaborn as sns
x = np.linspace(0, 15, 31)
data = np.sin(x) + np.random.rand(10, 31) + np.random.randn(10, 1)
fig, (ax,ax2) = plt.subplots(ncols=2, sharey=True)
ax = sns.tsplot(data=data,ax=ax, ci="sd")
def tsplot(ax, data,**kw):
x = np.arange(data.shape[1])
est = np.mean(data, axis=0)
sd = np.std(data, axis=0)
cis = (est - sd, est + sd)
ax.fill_between(x,cis[0],cis[1],alpha=0.2, **kw)
ax.plot(x,est,**kw)
ax.margins(x=0)
tsplot(ax2, data)
ax.set_title("sns.tsplot")
ax2.set_title("custom tsplot")
plt.show()
Run Code Online (Sandbox Code Playgroud)
import numpy as np; np.random.seed(1)
from scipy import stats
import matplotlib.pyplot as plt
import seaborn as sns
x = np.linspace(0, 15, 31)
data = np.sin(x) + np.random.rand(10, 31) + np.random.randn(10, 1)
fig, (ax,ax2) = plt.subplots(ncols=2, sharey=True)
ax = sns.tsplot(data=data,ax=ax)
def bootstrap(data, n_boot=10000, ci=68):
boot_dist = []
for i in range(int(n_boot)):
resampler = np.random.randint(0, data.shape[0], data.shape[0])
sample = data.take(resampler, axis=0)
boot_dist.append(np.mean(sample, axis=0))
b = np.array(boot_dist)
s1 = np.apply_along_axis(stats.scoreatpercentile, 0, b, 50.-ci/2.)
s2 = np.apply_along_axis(stats.scoreatpercentile, 0, b, 50.+ci/2.)
return (s1,s2)
def tsplotboot(ax, data,**kw):
x = np.arange(data.shape[1])
est = np.mean(data, axis=0)
cis = bootstrap(data)
ax.fill_between(x,cis[0],cis[1],alpha=0.2, **kw)
ax.plot(x,est,**kw)
ax.margins(x=0)
tsplotboot(ax2, data)
ax.set_title("sns.tsplot")
ax2.set_title("custom tsplot")
plt.show()
Run Code Online (Sandbox Code Playgroud)
我想这个被弃用的原因正是这个功能的使用相当有限,在大多数情况下,你最好只是直接绘制想要绘制的数据.
版本中引入了tsplot被叫的替代品.它不支持类似Numpy的" 宽格式 "数据,因此必须使用Pandas转换数据.lineplot0.9.0
x = np.linspace(0, 15, 31)
data = np.sin(x) + np.random.rand(10, 31) + np.random.randn(10, 1)
df = pd.DataFrame(data).melt()
sns.lineplot(x="variable", y="value", data=df)
Run Code Online (Sandbox Code Playgroud)