python - 如何在 seaborn 直方图上添加标准正态 pdf
问题描述
我想在用seaborn
.
import numpy as np
import seaborn as sns
x = np.random.standard_normal(1000)
sns.distplot(x, kde = False)
任何帮助,将不胜感激!
解决方案
scipy.stats.norm
可以轻松访问具有已知参数的正态分布的 pdf ;默认情况下,它对应于标准法线,mu=0
,sigma=1
。- 无论数据平均值位于何处(例如
mu=0
或mu=10
) ,此答案都有效
- 无论数据平均值位于何处(例如
- 在
python 3.8.11
,matplotlib 3.4.2
,中测试seaborn 0.11.2
- 这个问题和答案适用于轴级图;有关图形级别的图,请参阅如何在 seaborn displot 上绘制正态曲线
导入和数据
import numpy as np
import seaborn as sns
from scipy import stats
import matplotlib.pyplot as plt
# data
np.random.seed(365)
x = np.random.standard_normal(1000)
seaborn.histplot
ax = sns.histplot(x, kde=False, stat='density', label='samples')
# calculate the pdf
x0, x1 = ax.get_xlim() # extract the endpoints for the x-axis
x_pdf = np.linspace(x0, x1, 100)
y_pdf = scipy.stats.norm.pdf(x_pdf)
ax.plot(x_pdf, y_pdf, 'r', lw=2, label='pdf')
ax.legend()
seaborn.distplot
- 已弃用
- 为了正确对应您的采样数据,直方图应
显示密度而不是计数,因此请norm_hist=True
在seaborn.distplot
调用中使用。
ax = sns.distplot(x, kde = False, norm_hist=True, hist_kws={'ec': 'k'}, label='samples')
# calculate the pdf
x0, x1 = ax.get_xlim() # extract the endpoints for the x-axis
x_pdf = np.linspace(x0, x1, 100)
y_pdf = scipy.stats.norm.pdf(x_pdf)
ax.plot(x_pdf, y_pdf, 'r', lw=2, label='pdf')
ax.legend()
推荐阅读
- c++ - C++ Actor 框架处理 SIGINT
- python - Pygame 按钮软锁计算机
- php - 在 HTML 表单提交后 PHP 处理期间显示加载器
- azure - 在 Microsoft Edge 浏览器中忽略 MSAL 配置中的 navigateToLoginRequestUrl
- javascript - 将数组和 React 组件插入 HTML 元素
- selenium - Selenium 总是给出 org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element:
- typescript - 类型保护可以应用于接口的成员吗?
- android - 在片段中单击工具栏菜单项 (Kotlin)
- react-native - 在 React Native 中创建简单的网格布局
- c - Baremetal Nucleo-F446RE 打开 LED