python-3.x - seaborn histplot 和 displot 输出不匹配

标签 python-3.x numpy matplotlib seaborn histogram

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

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

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 个地 block ,密度为 1/2。

enter image description here

enter image description here

最佳答案

  • 根据 mwaskom 的建议在评论中,common_bins=False 将直方图设置为相同的形状,解决了忽略 binssharex 的问题,以及 多面图中的密度按每个方面中数据点的数量而不是方面的数量进行缩放。
  • 使用 common_norm=False 解决了 displotdensity 按绘图数量分割的问题

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

关于python-3.x - seaborn histplot 和 displot 输出不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68865538/

相关文章:

python - 简单利用 "import as"加载多场景数据?

python - Scipy:加速二维复积分的计算

python - 将带有回调的 Python 函数转换为可等待的 asyncio

python - 初始化字符串数据的numpy数组的奇怪行为

python - NumPy 数组中每行的唯一元素数

python - 在极坐标图中移动偏移文本位置

python - 如何清楚地绘制大型网络

python - 如何在Google Colab中显示点击图片的点的坐标?

mysql - 无法安装 MySQL-Connector 库

Python Pandas 添加 DataRow 修订号