使用 Seaborn `displot` (不是 `distplot`)在同一图表上显示多个直方图

问题描述 投票:0回答:2

Seaborn

distplot
已弃用。

使用

distplot
我得到下图

enter image description here

使用此代码:

import matplotlib.pyplot as plt
import seaborn as sns

sns.distplot(random.normal(loc=177.8, scale=10.2, size=1000), kde=True)
sns.distplot(random.normal(loc=165.1, scale=8.9, size=1000), kde=True)

plt.show()

我如何用

displot
达到同样的效果?如果我只是用
displot
代替
distplot
,直方图会单独显示。

python matplotlib seaborn
2个回答
0
投票

您想使用 displot 有什么具体原因吗?使用

histplot
可以实现您的目标。


0
投票

我有同样的问题并想到了这个,但我自己找到了答案。

将单行

displot
与 2 个 numpy 数组的列表以及
stat="density"
kde=True
一起使用可以解决问题。

sns.displot(
    [
        np.random.normal(loc=177.8, scale=10.2, size=1000),
        np.random.normal(loc=165.1, scale=8.9, size=1000),
    ],
    stat="density",
    kde=True,
    height=3,    # only to scale the graph
    aspect=1.6   # only to scale the graph
)

enter image description here

如果您还希望 KDE 曲线覆盖超过数据集的实际范围(请参见左下角),请使用

kde_kws=dict(cut=n)

 传递 
n > 0
kde_kws=dict(cut=3)
distplot
 默认值匹配。

sns.displot( [ np.random.normal(loc=177.8, scale=10.2, size=1000), np.random.normal(loc=165.1, scale=8.9, size=1000), ], stat="density", kde=True, kde_kws=dict(cut=3), height=3, # only to scale the graph aspect=1.6 # only to scale the graph )

enter image description here

以上结果在seaborn 0.13.2,numpy 1.26.4上。

© www.soinside.com 2019 - 2024. All rights reserved.