如何通过for循环自动为DataFrame每列绘制独立seaborn swarmplot
问题原因
你当前的循环代码没有为每一张图创建独立画布,所有sns.swarmplot的绘制结果默认叠加在同一个matplotlib坐标轴对象上,最终只会渲染出最后一次绘制的单张图表,无法输出9张独立图。
实现方案
方案1:逐张生成独立图表
适合需要单张查看、单独保存图片的场景,每次循环新建画布即可:
import seaborn as sns import matplotlib.pyplot as plt for col in df.columns: # 跳过作为x轴的分类列,避免生成无意义图表 if col == "Classification": continue # 新建独立画布 plt.figure(figsize=(6, 4)) sns.swarmplot(x='Classification', y=col, data=df) # 添加标题区分不同图表 plt.title(f'Distribution of {col} across Classification') # 如需本地存图可取消下一行注释 # plt.savefig(f'swarm_{col}.png', dpi=300, bbox_inches='tight') plt.show()
方案2:9张图按网格排布在同一画布
如果不想逐张翻看图,可创建子图网格,把9张图规整排列在一个大画布上(适配9列的3*3网格最常用):
import seaborn as sns import matplotlib.pyplot as plt # 提取需要绘制的数值列 target_cols = [c for c in df.columns if c != "Classification"] # 创建3行3列的子图网格 fig, axes = plt.subplots(nrows=3, ncols=3, figsize=(15, 12)) # 将二维坐标轴数组展平为一维,方便循环匹配 axes = axes.flatten() for ax, col in zip(axes, target_cols): # 指定当前绘图的子图坐标轴 sns.swarmplot(x='Classification', y=col, data=df, ax=ax) ax.set_title(f'{col} distribution') # 自动调整子图间距,避免文字重叠 plt.tight_layout() plt.show()
提示:如果数据集样本量很大,swarmplot会自动对点位做避让调整,单张图绘制速度较慢,可以根据需求替换为stripplot提升绘图效率。
内容的提问来源于stack exchange,提问作者DJC78
相关产品推荐
相关产品推荐

