如何将for循环生成的seaborn lmplot结果合并为多子图单个画布
解决方案
核心问题说明
不要用sns.lmplot,改用Axes级的sns.regplot:sns.lmplot是Figure级接口,调用时会自动创建独立画布,无法绑定到已有的子图网格上。而sns.regplot参数和lmplot完全一致,额外支持ax参数指定目标子图,刚好满足合并绘图的需求。
完整实现代码
import seaborn as sns import matplotlib.pyplot as plt # 你的已有变量定义 cols = ['a1', 'a2', 'a3', 'a4', 'a5', 'a6'] # data为你已加载的DataFrame # 按2列布局,6行对应6个a字段,共12个子图刚好放下所有图表 # 如果你一定要4行2列,可修改为nrows=4, ncols=2,多余的4个空坐标轴可手动隐藏 fig, axes = plt.subplots(nrows=len(cols), ncols=2, figsize=(10, 18)) axes = axes.flatten() plot_idx = 0 # 添加列顶部文本标注 fig.text(0.25, 0.96, 'value1 相关性', ha='center', fontsize=14, weight='bold') fig.text(0.75, 0.96, 'value2 相关性', ha='center', fontsize=14, weight='bold') for x_col in cols: # 绘制value1对应回归图 sns.regplot( x=x_col, y='value1', data=data, scatter_kws={"color": "black"}, line_kws={"color": "blue"}, ax=axes[plot_idx] ) axes[plot_idx].set_title(f'{x_col} & value1') axes[plot_idx].set_ylabel(x_col, fontsize=12) # 侧边加子图分组标签 plot_idx += 1 # 绘制value2对应回归图 sns.regplot( x=x_col, y='value2', data=data, scatter_kws={"color": "black"}, line_kws={"color": "blue"}, ax=axes[plot_idx] ) axes[plot_idx].set_title(f'{x_col} & value2') axes[plot_idx].set_ylabel('') # 第二列不需要重复显示侧边标签 plot_idx += 1 # 仅保留最外侧的坐标轴标签,避免重复 for ax in fig.get_axes(): ax.label_outer() # 自动调整布局避免标签重叠,预留顶部空间放列标题 plt.tight_layout() plt.subplots_adjust(top=0.94) plt.show()
4行2列适配说明
如果你必须按4行2列排布,总共有8个子图位置,你可以按需筛选8组变量绘图,多余的空坐标轴调用ax.axis('off')隐藏即可。
内容的提问来源于stack exchange,提问作者mjoy
相关产品推荐
相关产品推荐

