【问题标题】:seaborn histplot and displot output doesn't matchseaborn histplot 和 displot 输出不匹配
【发布时间】:2021-10-22 04:57:32
【问题描述】:
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()

  1. 设置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()

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()

更新

  • 按照mwaskom的建议,common_bins=False将直方图变成相同的形状,解决了忽略bins和sharex的问题。但是,density 似乎受到displot 中的地块数量的影响。
    • 如果displot中有3个地块,那么密度是histplot中显示的1/3;对于 2 个地块,密度为 1/2。

【问题讨论】:

    标签: python-3.x numpy matplotlib seaborn histogram


    【解决方案1】:
    • 正如mwaskom 在评论中所建议的那样,common_bins=False 将直方图变成相同的形状,解决了忽略bins 和sharex 的问题,并且多面图中的density 按比例缩放每个方面的数据点数,而不是方面的数量。
    • density 被displot 中的地块数分割的问题通过使用common_norm=False 得到解决

    绘图代码

    # 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()
    

    【讨论】:

      猜你喜欢
      • 2020-12-02
      • 2021-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-22
      • 1970-01-01
      • 2023-03-23
      • 2021-11-29
      相关资源
      最近更新 更多