简体   繁体   English

在 seaborn 分布图中曲线 Kernel 密度估计 (KDE)

[英]Curve the Kernel Density Estimate (KDE) in seaborn displot

When I try to plot my data in the form of histogram using seaborn displot:当我尝试使用 seaborn 显示直方图形式的 plot 数据时:

plot = sns.displot(
    data=z, kde=True, kind="hist", bins=3000, legend=True, aspect=1.8
).set(title='Error Distribution')

The curve for KDE is plotted in the form of straight lines instead of curves like here: KDE 的曲线以直线的形式绘制,而不是像这里这样的曲线: 错误分布 Is there a way to make the KDE lines cover all the bins of the histogram in a curved manner?有没有办法让 KDE 线以弯曲的方式覆盖直方图的所有 bin?

Instead of zooming in, you could use the bins to restrict to a certain range (via binrange=... ).您可以使用 bin 将其限制在某个范围内(通过binrange=... ),而不是放大。 To limit the range of the kde, you can use the clip keyword.要限制 kde 的范围,可以使用clip关键字。 Here is an example, first without setting the range:这是一个示例,首先没有设置范围:

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

放大显示

Here is how it would look with limiting the ranges for the histogram and the kde:以下是限制直方图和 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')

sns.displot 限制范围

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM