【问题标题】:How to add a standard normal pdf over a seaborn histogram如何在 seaborn 直方图上添加标准正态 pdf
【发布时间】:2019-03-25 07:45:25
【问题描述】:

我想在使用seaborn 构建的直方图上添加标准正态 pdf 曲线。

import numpy as np
import seaborn as sns 
x = np.random.standard_normal(1000)
sns.distplot(x, kde = False)

任何帮助将不胜感激!

【问题讨论】:

    标签: python seaborn histogram distribution


    【解决方案1】:
    • scipy.stats.norm 可让您轻松访问正态分布的 pdf
      已知参数;默认情况下,它对应于标准法线,mu=0sigma=1
      • 无论数据均值位于何处(例如 mu=0mu=10),此答案都有效
    • python 3.8.11matplotlib 3.4.2seaborn 0.11.2 中测试
    • 此问题和答案适用于轴级图;有关图形级别的图,请参阅How to draw a normal curve on 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 - 已弃用

    • 为了正确对应您的采样数据,直方图应
      显示密度而不是计数,因此请在 seaborn.distplot 调用中使用 norm_hist=True
    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()
    

    【讨论】:

    • 为什么你的情节只从 0.0 到 0.4?如果 y 轴的密度从 0 到 8,我该如何绘制正态分布?
    • @Jiren density:归一化,使得直方图的总面积等于 1。你可能想要这个question
    猜你喜欢
    • 2021-03-10
    • 2018-02-28
    • 2023-01-26
    • 1970-01-01
    • 2016-01-13
    • 2021-11-23
    • 1970-01-01
    • 1970-01-01
    • 2021-12-05
    相关资源
    最近更新 更多