gpt4 book ai didi

python - 如何在 matplotlib 中创建密度图?

转载 作者:IT老高 更新时间:2023-10-28 21:06:29 25 4
gpt4 key购买 nike

在 R 中,我可以通过以下方式创建所需的输出:

data = c(rep(1.5, 7), rep(2.5, 2), rep(3.5, 8),
rep(4.5, 3), rep(5.5, 1), rep(6.5, 8))
plot(density(data, bw=0.5))

Density plot in R

在python(使用matplotlib)中,我得到的最接近的是一个简单的直方图:

import matplotlib.pyplot as plt
data = [1.5]*7 + [2.5]*2 + [3.5]*8 + [4.5]*3 + [5.5]*1 + [6.5]*8
plt.hist(data, bins=6)
plt.show()

Histogram in matplotlib

我也试过 the normed=True parameter但除了尝试将高斯拟合到直方图之外,什么也得不到。

我最近的尝试是围绕 scipy.statsgaussian_kde,遵循网络上的示例,但到目前为止我一直没有成功。

最佳答案

五年后,当我谷歌“如何使用 python 创建内核密度图”时,这个帖子仍然出现在顶部!

今天,更简单的方法是使用 seaborn ,一个提供许多方便的绘图功能和良好的样式管理的包。

import numpy as np
import seaborn as sns
data = [1.5]*7 + [2.5]*2 + [3.5]*8 + [4.5]*3 + [5.5]*1 + [6.5]*8
sns.set_style('whitegrid')
sns.kdeplot(np.array(data), bw=0.5)

enter image description here

关于python - 如何在 matplotlib 中创建密度图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4150171/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com