You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何我的Seaborn catplot绘图会超出Matplotlib子图区域?

问题:Seaborn catplot 绘图超出子图范围,出现额外空图

我无法理解为何我的绘图会超出创建的子图范围,恳请指出问题所在。

异常效果如下:
绘图异常效果

我的代码片段:

figure, (ax1,ax2,ax3) = plt.subplots(1, 3, sharex=True)
figure.suptitle('repeat_retailer')

sns.catplot(ax= ax1, data=ds, x="repeat_retailer", y="distance_from_home", hue="fraud", jitter = True)

sns.catplot(ax= ax2, data=ds, x="repeat_retailer", y="distance_from_last_transaction", hue="fraud", jitter = True)

sns.catplot(ax= ax3, data=ds, x="repeat_retailer", y="ratio_to_median_purchase_price", hue="fraud", jitter = True)

plt.show()

问题原因

seaborn.catplot是FacetGrid类的接口,属于figure级别的绘图函数——它默认会创建新的画布,即便你指定了ax参数,它依然会生成自己的FacetGrid实例,这就和你手动创建的子图产生冲突,最终导致绘图位置偏移,还多出空的子图。

解决方案

改用axes级别的绘图函数,比如sns.stripplot(因为catplot默认的kind参数就是strip,也就是带抖动的散点图),它可以直接在你指定的子图上绘制,不会额外生成新画布。

修改后的代码:

import matplotlib.pyplot as plt
import seaborn as sns

# 可按需调整figsize优化布局
figure, (ax1, ax2, ax3) = plt.subplots(1, 3, sharex=True, figsize=(15, 6))
# 调整标题位置,避免和子图重叠
figure.suptitle('repeat_retailer', y=1.02)

sns.stripplot(ax=ax1, data=ds, x="repeat_retailer", y="distance_from_home", hue="fraud", jitter=True)
sns.stripplot(ax=ax2, data=ds, x="repeat_retailer", y="distance_from_last_transaction", hue="fraud", jitter=True)
sns.stripplot(ax=ax3, data=ds, x="repeat_retailer", y="ratio_to_median_purchase_price", hue="fraud", jitter=True)

# 自动调整子图间距,避免元素重叠
plt.tight_layout()
plt.show()

这样就能让三个图正确填充到你创建的1行3列子图中,不会再出现偏移和空图问题。


内容的提问来源于stack exchange,提问作者Rajath Agalkote

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 16:20:21