You need to enable JavaScript to run this app. 如何用seaborn的pairplot分多行绘制高维特征与因变量的关系图
优惠活动
大模型
产品
解决方案
定价
更多

如何用seaborn的pairplot分多行绘制高维特征与因变量的关系图

问题修复方案

根因说明

  • 你预先创建的画布和子图对象未被seaborn的pairplot函数使用:sns.pairplot属于seaborn的高层绘图接口,默认会自动生成独立的新画布实例,因此你预先声明的子图会变成空白框显示在顶部。
  • 每次循环调用pairplot都会生成独立的新画布,plt.savefig默认仅保存当前处于激活状态的最后一个画布,因此只能保存最后一行的绘图内容。

修正代码

你可以直接基于子图逐个绘制散点图,完全自主控制布局,避免pairplot的自动画布逻辑带来的问题,实现效果和你预期的分多行展示特征与y的关联完全一致:

from sklearn.datasets import load_boston
import math
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd

# 数据准备部分和你原代码一致
X, y = load_boston(return_X_y=True)
X = pd.DataFrame(X)
y = pd.DataFrame(y)
data = pd.concat([X, y], axis=1)

y_name = 'y'
features_names = [f'feature_{i}' for i in range(1, X.shape[1]+1)]  
column_names = features_names + [y_name]
data.columns = column_names

plot_size=3  # 单个子图的尺寸,可自行调整
num_plots_per_row = 5   # 每行展示的特征数量
total_features = len(features_names)
num_rows = math.ceil(total_features/num_plots_per_row)   # 总行数

# 统一创建画布和所有子图
fig, axes = plt.subplots(nrows=num_rows, ncols=num_plots_per_row, 
                         figsize=(plot_size*num_plots_per_row, plot_size*num_rows), 
                         facecolor='white')
# 把二维的axes数组展平,方便遍历
axes = axes.flatten()

for idx, feature in enumerate(features_names):
    # 在对应子图上绘制散点图,需要拟合线可以替换为sns.regplot
    sns.scatterplot(x=feature, y=y_name, data=data, ax=axes[idx])

# 隐藏多余的空子图(如果特征总数不能被每行数量整除的话)
for idx in range(total_features, len(axes)):
    axes[idx].axis('off')

# 调整子图间距
plt.tight_layout()
# 保存整张画布
plt.savefig('figure.png', dpi=150, bbox_inches='tight')
# 展示图片
plt.show()

如果你坚持要使用pairplot实现

你可以把每行的pairplot生成的画布保存为独立的文件:

# 其余数据准备部分和原代码一致
for i in range(num_plots_y):   
    start_index = i * num_plots_x
    end_index = (i+1) * num_plots_x
    if end_index > len(features_names): 
        end_index = len(features_names)
    g = sns.pairplot(x_vars=features_names[start_index:end_index], y_vars=y_name, data = data, height=plot_size)
    # 每行单独保存一个文件
    g.savefig(f'figure_row_{i+1}.png', dpi=150, bbox_inches='tight')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 11:57:04