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

使用seaborn循环遍历坐标轴批量绘制散点图的高效方法咨询

优化实现方案

方案1:遍历特征+平铺坐标轴批量绘图

只需要把连续特征整理成列表,再把子图坐标轴数组平铺后配对遍历即可,大幅减少重复代码:

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

# 1. 定义目标变量和连续变量列表
target_col = 'target'
cont_cols = [f'cont{i}' for i in range(9)]

# 2. 创建子图:9张图用3行3列刚好,也可以保留你原有的5行3列布局
fig, axes = plt.subplots(nrows=3, ncols=3, figsize=(16, 8))
# 把二维的axes数组平铺成一维,方便和特征列表一一配对
axes_flat = axes.flatten()

# 3. 遍历批量绘图
for col, ax in zip(cont_cols, axes_flat):
    sns.scatterplot(x=df[col], y=df[target_col], ax=ax)
    ax.set_title(f'{col} vs {target_col}', fontsize=10) # 可选:添加子图标题更清晰

# 如果保留5行3列的原始布局,多出来的6个空白子图可以隐藏
# for ax in axes_flat[len(cont_cols):]:
#     ax.axis('off')

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

后续如果要新增连续变量,只需要修改cont_cols列表即可,不需要新增重复的绘图代码。

方案2:用Seaborn FacetGrid 更简洁实现

如果不想手动遍历,也可以先把宽表转为长格式,直接用FacetGrid一次性绘制所有散点图,代码更符合Seaborn的API风格:

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

# 1. 把数据转为长格式,仅保留需要的连续变量和目标变量
cont_cols = [f'cont{i}' for i in range(9)]
df_long = df.melt(id_vars='target', value_vars=cont_cols, var_name='cont_feature', value_name='cont_value')

# 2. 用FacetGrid批量绘图
g = sns.FacetGrid(df_long, col='cont_feature', col_wrap=3, height=2, aspect=1.5)
g.map(sns.scatterplot, 'cont_value', 'target')
g.set_axis_labels('', 'target') # 统一设置y轴标签
g.set_titles(col_template='{col_name} vs target') # 统一设置子图标题
plt.tight_layout()
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 13:39:02