我使用
sns.distplot
如何从Matplotlib Axes(由distplot返回)获取数据点,以绘制观测值的单变量分布。但我不仅需要图表,还需要数据点。
sns.distplot
如何从Matplotlib Axes(由distplot返回)获取数据点,以绘制观测值的单变量分布。但我不仅需要图表,还需要数据点。
sns.distplot(x).get_lines()[0].get_data()
这将返回两个包含线条的x和y值的numpy数组。
对于条形图,信息存储在:
sns.distplot(x).patches
你可以通过函数patches.get_height()
来访问该条形图的高度:[h.get_height() for h in sns.distplot(x).patches]
如果你想获取直方图的 kde 值,可以使用 scikit-learn 的 KernelDensity
函数:
import numpy as np
import pandas as pd
from sklearn.neighbors import KernelDensity
ds=pd.read_csv('data-to-plot.csv')
X=ds.loc[:,'Money-Spent'].values[:, np.newaxis]
kde = KernelDensity(kernel='gaussian', bandwidth=0.75).fit(X) #you can supply a bandwidth
#parameter.
x=np.linspace(0,5,100)[:, np.newaxis]
log_density_values=kde.score_samples(x)
density=np.exp(log_density_values)
array([1.88878660e-05, 2.04872903e-05, 2.21864649e-05, 2.39885206e-05,
2.58965064e-05, 2.79134003e-05, 3.00421245e-05, 3.22855645e-05,
3.46465903e-05, 3.71280791e-05, 3.97329392e-05, 4.24641320e-05,
4.53246933e-05, 4.83177514e-05, 5.14465430e-05, 5.47144252e-05,
5.81248850e-05, 6.16815472e-05, 6.53881807e-05, 6.92487062e-05,
7.32672057e-05, 7.74479375e-05, 8.17953578e-05, 8.63141507e-05,
..........................
..........................
3.93779919e-03, 4.15788216e-03, 4.38513011e-03, 4.61925890e-03,
4.85992626e-03, 5.10672757e-03, 5.35919187e-03, 5.61677855e-03])
density=np.exp(log_density_values)
而不是 density=np.exp(log_density)
。 - mchl_k在较新版本的seaborn中,情况已经不再如此。首先,distplot已被替换为displot。其次,在调用get_lines()时,会出现一个错误消息AttributeError: 'FacetGrid'对象没有属性'get_lines'。
displot
现在返回一个FacetGrid
,您必须访问该FacetGrid
的各个轴以访问其lines
或patches
属性。请参见https://stackoverflow.com/a/75721847/13636407。 - paime这将获得您想要的 KDE 曲线
line = sns.distplot(data).get_lines()[0]
plt.plot(line.get_xdata(), line.get_ydata())
distplot
之前,Axes
上存在任何线条,你将会获取到那些线条上的数据。 - tacaswelll = [[h.xy[0], h.get_width(), h.get_height()] for h in sns.distplot(x).patches]
- KamKam