matplotlib 从sns.kdeplot提取数据

flvtvl50  于 2023-03-19  发布在  其他
关注(0)|答案(2)|浏览(160)

是否可以在绘图前从sns.kdeplot()中提取数据?即,不使用函数y.get_lines()[0].get_data() post plotting

gudnpqoy

gudnpqoy1#

这可以通过从matplotlib Axes对象中提取线数据来完成:

import numpy as np
from seaborn import kdeplot

my_data = np.random.randn(1000)
my_kde = kdeplot(my_data)
line = my_kde.lines[0]
x, y = line.get_data()

fig, ax = plt.subplots()
ax.plot(x[x>0], y[x>0])

可选地,statmodels方式:

import statsmodels.api as sm

dens = sm.nonparametric.KDEUnivariate(np.random.randn(1000))
dens.fit()
x =np.linspace(0,1,100) #restrict range to (0,1)
y = dens.evaluate(x)
plt.plot(x,y)
kyvafyod

kyvafyod2#

基于statsmodels's documentation

import numpy as np
import seaborn as sns
import statsmodels.api as sm
import matplotlib.pyplot as plt

# generate bimodal disrtibution
X1 = np.random.normal(100, 10, 250)
X2 = np.random.normal(10, 20, 250)
X = np.concatenate([X1, X2])

# get density from seaborn
x, y = sns.kdeplot(X).lines[0].get_data()

# get density from statsmodel
kde = sm.nonparametric.KDEUnivariate(X).fit()
xx, yy = (kde.support, kde.density)

# compare outputs
plt.plot(x, y, label='from sns')
plt.plot(xx, yy, label='from statsmodels')
plt.legend()

相关问题