在 seaborn displot 中曲线核密度估计(KDE)
Curve the Kernel Density Estimate (KDE) in seaborn displot
当我尝试使用 seaborn displot 以直方图的形式绘制数据时:
plot = sns.displot(
data=z, kde=True, kind="hist", bins=3000, legend=True, aspect=1.8
).set(title='Error Distribution')
KDE 的曲线是以直线的形式绘制的,而不是像这里这样的曲线:
有没有办法让 KDE 线以曲线方式覆盖直方图的所有 bins?
您可以使用 bin 限制在一定范围内(通过 binrange=...
),而不是放大。要限制 kde 的范围,可以使用 clip
关键字。下面是一个例子,先不设置范围:
from matplotlib import pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np
# first, create some test data
slatm = np.random.normal(-.9, .4, size=(10000, 10)).max(axis=1)
split = np.random.normal(-.1, .1, size=(10000, 10)).max(axis=1)
split[0] = 200 # ad an extreme far value to the dataset
z = pd.DataFrame({'slatm': slatm, 'split': split})
g = sns.displot(data=z, kde=True, kind="hist", bins=3000, legend=True, aspect=1.8)
g.set(title='Error Distribution')
g.ax.set_xlim(-1, 0.5) # zoom in via the x limits
下面是限制直方图和 kde 范围的情况:
min_x, max_x = -1, 0.5
g = sns.displot(data=z, kde=True, kind="hist", bins=30, binrange=(min_x, max_x), legend=True, aspect=1.8,
kde_kws={'clip': (min_x, max_x)})
g.set(title='Error Distribution')
当我尝试使用 seaborn displot 以直方图的形式绘制数据时:
plot = sns.displot(
data=z, kde=True, kind="hist", bins=3000, legend=True, aspect=1.8
).set(title='Error Distribution')
KDE 的曲线是以直线的形式绘制的,而不是像这里这样的曲线:
您可以使用 bin 限制在一定范围内(通过 binrange=...
),而不是放大。要限制 kde 的范围,可以使用 clip
关键字。下面是一个例子,先不设置范围:
from matplotlib import pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np
# first, create some test data
slatm = np.random.normal(-.9, .4, size=(10000, 10)).max(axis=1)
split = np.random.normal(-.1, .1, size=(10000, 10)).max(axis=1)
split[0] = 200 # ad an extreme far value to the dataset
z = pd.DataFrame({'slatm': slatm, 'split': split})
g = sns.displot(data=z, kde=True, kind="hist", bins=3000, legend=True, aspect=1.8)
g.set(title='Error Distribution')
g.ax.set_xlim(-1, 0.5) # zoom in via the x limits
下面是限制直方图和 kde 范围的情况:
min_x, max_x = -1, 0.5
g = sns.displot(data=z, kde=True, kind="hist", bins=30, binrange=(min_x, max_x), legend=True, aspect=1.8,
kde_kws={'clip': (min_x, max_x)})
g.set(title='Error Distribution')