seaborn 的 histplot 和 displot 输出不匹配。

3
import seaborn as sns
import matplotlib.pyplot as plt

# sample data: wide
dfw = sns.load_dataset("penguins", cache=False)[['bill_length_mm', 'bill_depth_mm']].dropna()

# sample data: long
dfl = dfw.melt(var_name='bill_size', value_name='vals')

seaborn.displot

  1. 忽略 'sharex': False,但 'sharey' 可用
  2. 忽略 bins
fg = sns.displot(data=dfl, x='vals', col='bill_size', kde=True, stat='density', bins=12, height=4, facet_kws={'sharey': False, 'sharex': False})
plt.show()

enter image description here

  • 设置xlim没有任何影响。
  • fg = sns.displot(data=dfl, x='vals', col='bill_size', kde=True, stat='density', bins=12, height=4, facet_kws={'sharey': False, 'sharex': False})
    axes = fg.axes.ravel()
    axes[0].set_xlim(25, 65)
    axes[1].set_xlim(13, 26)
    plt.show()
    

    enter image description here

    seaborn.histplot

    fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(8, 4))
    
    sns.histplot(data=dfw.bill_length_mm, kde=True, stat='density', bins=12, ax=ax1)
    sns.histplot(data=dfw.bill_depth_mm, kde=True, stat='density', bins=12, ax=ax2)
    fig.tight_layout()
    plt.show()
    

    enter image description here

    更新

    • 根据mwaskom的建议,使用common_bins=False可以使直方图形状相同,解决了忽略binssharex的问题。然而,在displot中的密度会受到绘图数量的影响。
      • 如果在displot中有3个图,则密度是histplot中显示密度的1/3;对于2个图,则密度为1/2。

    enter image description here

    enter image description here

    1个回答

    3
    • 按照mwaskom在评论中的建议,common_bins=False使直方图形状相同,解决了忽略binssharex的问题。而且在分面绘图中,density基于每个facet中的数据点数量进行缩放,而不是基于facets数量进行缩放。
    • 通过使用common_norm=False解决了displot中涉及多个绘图时因绘图数量而拆分density的问题。

    enter image description here

    enter image description here

    绘图代码

    # displot
    fg = sns.displot(data=dfl, x='vals', col='bill_size', kde=True, stat='density', bins=12, height=4,
                     facet_kws={'sharey': False, 'sharex': False}, common_bins=False, common_norm=False)
    
    fg.fig.subplots_adjust(top=0.85)
    fg.fig.suptitle('Displot with common_bins & common_norm as False')
    plt.show()
    
    # histplot
    fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(8, 4))
    
    sns.histplot(data=dfw.bill_length_mm, kde=True, stat='density', bins=12, ax=ax1)
    sns.histplot(data=dfw.bill_depth_mm, kde=True, stat='density', bins=12, ax=ax2)
    
    fig.subplots_adjust(top=0.85)
    fig.suptitle('Histplot')
    
    fig.tight_layout()
    plt.show()
    

    网页内容由stack overflow 提供, 点击上面的
    可以查看英文原文,
    原文链接