使用 Seaborn 的分布图的部分阴影

Partial shade of distribution plot using Seaborn

以下简单代码:

import numpy as np
import seaborn as sns
dist = np.random.normal(loc=0, scale=1, size=1000)
ax = sns.kdeplot(dist, shade=True);

生成下图:

我只想把所有东西都涂上阴影(或留下一些 x 值)。最简单的方法是什么?我已经准备好使用 Seaborn 以外的东西了。

调用ax = sns.kdeplot(dist, shade=True)后,ax.get_lines()最后一行对应kde密度曲线:

ax = sns.kdeplot(dist, shade=True)
line = ax.get_lines()[-1]

您可以使用 line.get_data:

提取对应于该曲线的数据
x, y = line.get_data()

获得数据后,例如,您可以通过选择这些点并调用 ax.fill_between:

来为 x > 0 对应的区域添加阴影
mask = x > 0
x, y = x[mask], y[mask]
ax.fill_between(x, y1=y, alpha=0.5, facecolor='red')

import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
dist = np.random.normal(loc=0, scale=1, size=1000)
ax = sns.kdeplot(dist, shade=True)
line = ax.get_lines()[-1]
x, y = line.get_data()
mask = x > 0
x, y = x[mask], y[mask]
ax.fill_between(x, y1=y, alpha=0.5, facecolor='red')
plt.show()

使用 seaborn 通常可以很好地绘制标准图,但当出现一些自定义要求时,回退到 matplotlib 通常会更容易。

因此可以先计算核密度估计值,然后将其绘制在感兴趣的区域中。

import scipy.stats as stats
import numpy as np
import matplotlib.pyplot as plt
plt.style.use("seaborn-darkgrid")

dist = np.random.normal(loc=0, scale=1, size=1000)
kde = stats.gaussian_kde(dist)
# plot complete kde curve as line
pos = np.linspace(dist.min(), dist.max(), 101)
plt.plot(pos, kde(pos))
# plot shaded kde only right of x=0.5
shade = np.linspace(0.5,dist.max(), 101)
plt.fill_between(shade,kde(shade), alpha=0.5)

plt.ylim(0,None)
plt.show()