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

2024-04-27 06:04:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Seaborn绘制两个数据集的KDE。但这两款KDE都在缩小规模

我的代码:

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

这给了我:

enter image description here

但我想让它们与它们所代表的数据成比例地缩放。所以 比如:

enter image description here

有什么建议吗


Tags: 数据代码true绘制代表seaborn规模sns
1条回答
网友
1楼 · 发布于 2024-04-27 06:04:39

计数只能与某些箱子相关。据我所知,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

相关问题 更多 >