seaborn histplot 和 displot 输出不匹配

seaborn histplot and displot output doesn't match

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 将直方图变为相同的形状,解决了忽略 binssharex 的问题,以及 density 在分面图中按每个分面中的数据点数而不是分面数缩放。
  • densitydisplot 中的地块数量分割的问题已通过使用 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()