循环遍历Pandas列绘制countplot仅显示首个图表的解决方法求助
问题描述
我有一个包含896k行的数据集,结构如下:
Name SM_Presence TL_presence LS_presence VC Eligible Aaron 0 0 0 0 0 John 1 0 1 1 0 Alex 0 1 1 0 0 Steve 0 0 1 0 1
我需要为这些特征全部绘制countplot,于是编写了如下代码:
lists = ['SM_Presence','TL_presence','LS_presence','VC','Eligible'] for i in lists: sns.countplot(x = i, data = df) plt.show()
但该代码仅打印第一个特征SM_Presence的countplot,无法显示其他图表,请问如何一次性打印所有图表?
解决方案
问题出在:循环中连续绘制的图表都叠加在同一个画布上,最后plt.show()只输出这一个画布,导致看起来只有第一个图表。以下是两种可行的解决方法:
方法1:逐个弹出显示图表
在循环内部每次绘制完成后调用plt.show(),让每个图表单独显示:
import seaborn as sns import matplotlib.pyplot as plt lists = ['SM_Presence','TL_presence','LS_presence','VC','Eligible'] for col in lists: sns.countplot(x=col, data=df) plt.title(f'Count of {col}') # 可选:添加标题便于区分 plt.show()
方法2:子图布局统一展示
如果想要所有图表在同一画布中排列,方便对比,可以使用matplotlib的子图功能,示例采用2行3列的布局适配5个特征:
import seaborn as sns import matplotlib.pyplot as plt lists = ['SM_Presence','TL_presence','LS_presence','VC','Eligible'] # 创建2行3列的子图网格,设置画布大小 fig, axes = plt.subplots(nrows=2, ncols=3, figsize=(16, 9)) # 将二维子图数组转为一维,方便循环遍历 axes = axes.flatten() for idx, col in enumerate(lists): # 指定子图绘制countplot sns.countplot(x=col, data=df, ax=axes[idx]) axes[idx].set_title(f'Countplot of {col}') axes[idx].set_xlabel(col) # 隐藏多余的第6个空子图 axes[-1].axis('off') # 自动调整子图间距,避免标题、标签重叠 plt.tight_layout() plt.show()
内容的提问来源于stack exchange,提问作者Patrik
相关产品推荐
相关产品推荐

