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

6

下面是简单的代码:

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以外的其他东西。

2个回答

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

enter image description here


Axes类的文档在此处链接。它提到了get_lines,这里是get_data的文档。 - unutbu
1
但说实话,我主要是通过在Stackoverflow上看到其他人的解决方案,偶尔通过阅读源代码来学习这些东西。IPython的tab-completion在你想发现对象属性和方法时是一个巨大的帮助。 - unutbu

5

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接