【问题标题】:Add a normal distribution to seaborn 2D histogram向 seaborn 2D 直方图添加正态分布
【发布时间】:2021-03-10 15:00:41
【问题描述】:

是否可以从 seaborn 中获取直方图并添加正态分布?

假设我有类似这样的散点图和直方图from the documentation.

import seaborn as sns
penguins = sns.load_dataset("penguins")
sns.jointplot(data=penguins, x="bill_length_mm", y="bill_depth_mm");
plt.savefig('deletethis.png', bbox_inches='tight')

我可以像下图那样在侧面叠加分布吗?

import matplotlib.pyplot as plt
import numpy as np
from scipy.stats import norm

x = np.random.normal(size=100000)

# Plot histogram in one-dimension
plt.hist(x,bins=80,density=True)
xvals = np.arange(-4,4,0.01)
plt.plot(xvals, norm.pdf(xvals),label='$N(0,1)$')
plt.legend();

【问题讨论】:

    标签: python matplotlib plot seaborn histogram


    【解决方案1】:

    下面给出了一个核密度估计,它显示了分布(如果它是正常的):

    g = sns.JointGrid(data=penguins, x="bill_length_mm", y="bill_depth_mm")
    g.plot_joint(sns.scatterplot, s=100, alpha=.5)
    g.plot_marginals(sns.histplot, kde=True)
    

    下面在坐标轴的直方图上叠加了一个正态分布。

    import seaborn as sns
    import numpy as np
    import pandas as pd
    from scipy.stats import norm
    
    df1 = penguins.loc[:,["bill_length_mm", "bill_depth_mm"]]
    
    axs = sns.jointplot("bill_length_mm", "bill_depth_mm", data=df1)
    axs.ax_joint.scatter("bill_length_mm", "bill_depth_mm", data=df1, c='r', marker='x')
    
    axs.ax_marg_x.cla()
    axs.ax_marg_y.cla()
    sns.distplot(df1.bill_length_mm, ax=axs.ax_marg_x, fit=norm)
    sns.distplot(df1.bill_depth_mm, ax=axs.ax_marg_y, vertical=True, fit=norm)
    

    【讨论】:

      猜你喜欢
      • 2021-12-04
      • 2019-03-25
      • 2019-09-26
      • 2016-09-16
      • 2014-01-30
      • 1970-01-01
      • 2017-03-02
      • 2011-12-28
      • 2019-10-06
      相关资源
      最近更新 更多