带有子图的猫图是否有限制?

Aar*_*ron 6 python subplot categorical-data seaborn

Seaborn 的猫图似乎无法与 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")
Run Code Online (Sandbox Code Playgroud)

输出: 奇怪没有输出 奇怪的没有输出2 最后输出

小智 7

Catplot 是图形级函数,但不能使用轴。尝试使用条形图代替。

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])
Run Code Online (Sandbox Code Playgroud)


She*_*ore 2

您需要catplot在绘图时将创建的轴传递给seaborn。以下是演示这一点的示例答案。有几件事

  • 我建议使用add_subplot创建像你这样的子图
  • 仍然会catplot返回一个轴对象,可以使用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()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • 我似乎无法在 catplot 中放置轴,因为我收到此错误:“UserWarning:catplot 是图形级函数,不接受目标轴。” (11认同)
  • 请注意,自 seaborn 0.11 起,“catplot”(以及类似的图形级函数)不再接受“ax=”参数。您需要直接调用底层轴级函数(例如`stripplot(...., ax=...)`)或将数据帧转换为“长格式”(通过pandas `melt`)。 (3认同)