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

问题描述 投票:2回答:2

遵循简单的代码:

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

得到以下图像:

enter image description here

我想只遮蔽一切(或留下一些x值)。什么是最简单的方法?我准备使用Seaborn以外的东西。

python matplotlib data-visualization distribution seaborn
2个回答
3
投票

在调用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()

获得数据后,您可以通过选择这些点并调用x > 0来对与ax.fill_between对应的区域进行着色:

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()

enter image description here


3
投票

使用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()

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.