将KDE添加到直方图上

时间:2015-10-24 21:14:29

标签: python matplotlib

我想在直方图中添加密度图。我对pdf功能有所了解,但我感到困惑,其他类似的问题也无济于事。

from scipy.stats import * 
from numpy import*
from matplotlib.pyplot import*
from random import*

nums = []
N = 100
for i in range(N):
    a = randint(0,9)
    nums.append(a)

bars= [0,1,2,3,4,5,6,7,8,9]
alpha, loc, beta=5, 100, 22

hist(nums,normed= True,bins = bars)


show()

我正在寻找类似的东西

enter image description here

2 个答案:

答案 0 :(得分:8)

from scipy import stats
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(41)

N = 100
x = np.random.randint(0, 9, N)
bins = np.arange(10)

kde = stats.gaussian_kde(x)
xx = np.linspace(0, 9, 1000)
plt, ax = plt.subplots(figsize=(8,6))
ax.hist(x, normed=True, bins=bins, alpha=0.3)
ax.plot(xx, kde(xx))

plot

答案 1 :(得分:1)

这是使用 seaborn 0.11.1 和 pandas 1.1.5 的解决方案:

import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import numpy as np

N = 100
nums = [np.random.randint(i-i, 9) for i in range(N)]
df = pd.DataFrame(nums, columns=["value"])

fig, ax1 = plt.subplots()
sns.kdeplot(data=df, x="value", ax=ax1)
ax1.set_xlim((df["value"].min(), df["value"].max()))
ax2 = ax1.twinx()
sns.histplot(data=df, x="value", discrete=True, ax=ax2)

enter image description here

请注意我如何使用 numpy 生成随机值,因为我需要实际值,而不是生成器。最后一行中的 discrete=True 确保刻度居中。