seaborn.histplot
生成的直方图和seaborn.displot
不匹配。sns.displot
的默认绘图是kind='hist'
- 使用
python3.8.11
、seaborn 0.11.2
和matplotlib 3.4.2
测试 - 为什么输出不匹配,如何解决?
- 预期是,给定
bins
,相应地 block 的density
应该匹配。bins
被传递给numpy.histogram_bin_edges
- Visualizing distributions of data 中包含的信息没有解决问题。
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
- 忽略
'sharex': False
,尽管'sharey'
有效 - 忽略
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()
- 设置
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
的问题。但是,密度
似乎受displot
中绘图数量的影响。- 如果
displot
中有 3 个图,则密度为histplot
中显示的密度的 1/3;对于 2 个地 block ,密度为 1/2。
- 如果
最佳答案
- 根据 mwaskom 的建议在评论中,
common_bins=False
将直方图设置为相同的形状,解决了忽略bins
和sharex
的问题,以及多面图中的密度
按每个方面中数据点的数量而不是方面的数量进行缩放。 - 使用
common_norm=False
解决了displot
中density
按绘图数量分割的问题
剧情代码
# 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/