【问题标题】:Plotting Two Histograms. Why can't one have kde while other not have it?绘制两个直方图。为什么一个人没有kde而另一个人没有?
【发布时间】:2020-09-09 20:23:25
【问题描述】:

所以我正在学习 Kaggle 数据可视化微课程,并学习了绘制直方图的课程。 所以练习要求绘制两个直方图,我这样做了,它奏效了,但是如果我在其中一个图上添加 kde = False,则只有该图可见,另一个图不显示:

           `sns.distplot(a = cancer_b_data['Area (mean)'], kde = False) 
            sns.distplot(a = cancer_m_data['Area (mean)'])  `     

不知道我听起来有多愚蠢,但任何澄清都会有所帮助。谢谢

【问题讨论】:

    标签: python data-visualization seaborn histogram


    【解决方案1】:

    使用默认的kde=True,kde 被归一化,使得曲线下的面积为 1。为了一起在同一个图中,直方图也将被归一化,使得所有条形的完整面积总和为 1。

    使用kde=False,默认直方图将显示频率(每个 bin 的计数),这是更大的数字。如果您将两者都显示在具有相同轴的同一图中,则归一化直方图不会消失,但会非常小。使用缩放工具,您可以验证它是否仍然存在。要查看相同大小的两者,可以使用sns.distplot(..., kde=False, norm_hist=True)

    您会注意到,两个直方图不使用相同的 bin 边界。这些边界是使用样本数以及各个样本集的最小值和最大值来计算的。

    要真正比较两个直方图,可以设置明确的 bin,因此两者都使用相同的 bin 边界。

    以下代码和绘图比较了比较直方图的 3 种不同方式:

    import matplotlib.pyplot as plt
    import numpy as np
    import seaborn as sns
    
    x1 = np.random.randn(100).cumsum()
    x2 = np.random.randn(100).cumsum()
    fig, (ax1, ax2, ax3) = plt.subplots(ncols=3, figsize=(15, 4))
    
    sns.distplot(a=x1, kde=False, ax=ax1)
    sns.distplot(a=x2, ax=ax1)
    ax1.set_title('one histogram without kde')
    
    sns.distplot(a=x1, kde=False, norm_hist=True, ax=ax2)
    sns.distplot(a=x2, ax=ax2)
    ax2.set_title('setting norm_hist=True')
    
    xmin = min(x1.min(), x2.min())
    xmax = max(x1.max(), x2.max())
    bins = np.linspace(xmin, xmax, 11)
    sns.distplot(a=x1, kde=False, norm_hist=True, bins=bins, ax=ax3)
    sns.distplot(a=x2, bins=bins, ax=ax3)
    ax3.set_title('using the same bins')
    
    plt.tight_layout()
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-30
      • 1970-01-01
      • 2012-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-06
      • 2020-06-19
      相关资源
      最近更新 更多