如何缩放具有不同频率的多个KDE图?

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

我正在使用Seaborn绘制两个数据集的KDE。但是两个KDE的比例都缩小了。

我的代码:

sns.kdeplot(CDMX['EDAD'], shade=True)
sns.kdeplot(eduacion_superior['EDAD'], shade=True)

这给了我:

enter image description here

但是我想根据它们表示的数据按比例缩放它们。所以,类似于:

enter image description here

有什么建议吗?

python matplotlib seaborn
1个回答
1
投票

相对于某些垃圾箱,计数仅有意义。据我所知,seaborn的distplot可以显示带有计数的直方图,但是只要您还想要kde,就可以将直方图和kde都按比例缩小以得到总面积为1。

要获得类似于所要求的图,标准的matplotlib可以绘制用Scipy计算的kde。要获得计数,必须决定如何对数据进行分箱,因为计数取决于相关直方图的分箱大小。最简单的方法是在x轴上每单位有一个垃圾箱(因此,每岁一次)。

这里是一些示例代码。首先,生成一些随机测试数据。然后绘制两个直方图,每个年龄段都有垃圾箱。在第二个图中,绘制了相同数据的kde,并根据数据集的大小进行缩放。

import matplotlib.pyplot as plt
import numpy as np
from scipy import stats

cdmx_edad = np.random.chisquare(15, 10000)+10
ed_sup_edad = np.random.chisquare(20, 5000)+10

fig, (ax1, ax2) = plt.subplots(nrows=2, sharex=True)
bins = np.arange(10,61,1)
ax1.hist(cdmx_edad, bins=bins, color='r', alpha=0.4, label='CDMX edad')
ax1.hist(ed_sup_edad, bins=bins, color='b', alpha=0.4, label='Educación superior edad')
ax1.legend()

cdmx_kde = stats.gaussian_kde(cdmx_edad)
ed_sup_kde = stats.gaussian_kde(ed_sup_edad)
x = np.linspace(10,61,500)
cdmx_curve = cdmx_kde(x)*cdmx_edad.shape[0]
ed_sup_curve = ed_sup_kde(x)*ed_sup_edad.shape[0]
# ax2.plot(x, cdmx_curve, color='r')
ax2.fill_between(x, 0, cdmx_curve, color='r', alpha=0.4, label='CDMX edad')
# ax2.plot(x, ed_sup_curve, color='b')
ax2.fill_between(x, 0, ed_sup_curve, color='b', alpha=0.4, label='Educación superior edad')
ax2.legend()
plt.show()

resulting plot

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