带有子图的 catplot 有限制吗?

Is there a restriction on catplot with subplot?

Seaborn 的 catplot 似乎无法与 plt.subplots() 一起使用。我不确定这里有什么问题,但我似乎无法将它们并排放置。

#Graph 1
plt.subplot(121)
sns.catplot(x="HouseStyle",y="SalePrice",data=df,kind="swarm")

#Graph 2
plt.subplot(122)
sns.catplot(x="LandContour",y="SalePrice",data=df,kind="swarm")

输出:

您需要在绘图时将创建的轴传递给 seaborn 的 catplot。以下是证明这一点的示例答案。一些事情

  • 我建议使用 add_subplot 来创建像您这样的子图
  • catplot 仍然是 return 轴对象,可以使用 plt.close() 关闭其中括号内的数字对应于数字计数。有关 close()
  • 的更多详细信息,请参阅

完整的可重现答案

import seaborn as sns
import matplotlib.pyplot as plt

exercise = sns.load_dataset("exercise")

fig = plt.figure()

ax1 = fig.add_subplot(121)
g = sns.catplot(x="time", y="pulse", hue="kind", data=exercise, ax=ax1) # pass ax1

ax2 = fig.add_subplot(122)
g = sns.catplot(x="time", y="pulse", hue="kind", data=exercise, ax=ax2) # pass ax2

plt.close(2)
plt.close(3)
plt.tight_layout()

感谢 Sheldore 提供使用 close() 的想法。我试过这种方法,它奏效了。

_, ax = plt.subplots(2, 3, figsize=(20,10))
for n, feat in enumerate(cat_feats):
        sns.catplot(x='feat', kind='count', data=df, ax=ax[n//3][n%3])
        plt.close()

Catplot 是图形级函数,而您不能使用轴。尝试使用 stripplot

fig, axs = plt.subplots (1, 2, figsize=(25, 15))
sns.stripplot(x='category_col', y='y_col_1', data=df, ax=axs[0])
sns.stripplot(x='category_col', y='y_col_2', data=df, ax=axs[1])