首页 > 解决方案 > 如何彼此相邻显示seaborn地块?使用 pyplot 风格(不是 OO)?

问题描述

我想显示三个具有相同数据但不同类型的图的图。

以下代码将显示它们一个在另一个之下:

plt.figure()

sns.displot(t['Age'], kind="kde", rug = True)

sns.displot(t['Age'], kind="hist", bins = 25)

sns.displot(t['Age'], kind="ecdf")

plt.show()

使用 pyplot 绘图和非 OO 样式,我可以执行以下操作:

plt.figure(figsize=(12,4))

plt.subplot(131)
plt.hist(t['Age'], bins = 22)

plt.subplot(132)
plt.hist(t['Age'], bins = 33)

plt.subplot(133)
plt.hist(t['Age'], bins = int(t['Age'].max() - t['Age'].min()))

plt.show()

看起来非常好。 在这里你可以看到

为什么我不能这样做?

plt.figure(figsize=(12,4))

plt.subplot(131)
sns.displot(t['Age'], kind="kde", rug = True)
plt.subplot(132)
sns.displot(t['Age'], kind="hist", bins = 25)
plt.subplot(133)
sns.displot(t['Age'], kind="ecdf")

plt.show()

这看起来很糟糕 它看起来如何......似乎它们被卡在左边框中

如果没有这个 oo 符号,是否可以做到这一点?

fig, (ax1, ax2, ax3) = plt.subplots(1,3)
sns.displot(..., ax=ax1)
sns.displot(..., ax=ax2)
...

标签: pythonmatplotlibseaborn

解决方案


好的,在对 seaborn api进行了简短但非常有启发性的研究后,我得出了一个结论:

displot() 非常灵活,您可以制作多种图形,有趣的是每种图形都有自己的功能。

你可以这样做:

plt.figure(figsize=(16,4))

plt.subplot(141)
sns.kdeplot(t['Age'])
plt.subplot(142)
sns.histplot(t['Age'])
plt.subplot(143)
sns.ecdfplot(t['Age'])
plt.subplot(144)
sns.rugplot(t['Age'])

plt.show()

避免OO风格。 结果

但在这种情况下,让 rugplot 和 kde 图在相同的轴上并不容易。当你尝试:

plt.figure(figsize=(12,4))

plt.subplot(131)
sns.kdeplot(t['Age'])
plt.subplot(132)
sns.histplot(t['Age'])
plt.subplot(133)
sns.ecdfplot(t['Age'])
plt.subplot(131)
sns.rugplot(t['Age'])

plt.show()

你得到这个警告: 所以你不应该因为这个警告而使用它。

如果你想让它看起来很漂亮,你需要更多的控制,OO-Style 可能是最好的解决方案:

fig, axes = plt.subplots(1,3, figsize=(12,4))

sns.kdeplot(t['Age'], ax = axes[0])
sns.histplot(t['Age'], ax = axes[1])
sns.ecdfplot(t['Age'], ax = axes[2])
sns.rugplot(t['Age'], ax = axes[0])

plt.show()

非常好


推荐阅读