You need to enable JavaScript to run this app. 如何在Python中使用for循环绘制多张子图并优化代码优雅性
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中使用for循环绘制多张子图并优化代码优雅性

优化实现方案

核心优化点

  • 用axes.flat将子图二维数组展平为一维迭代器,配合zip直接匹配分类变量和对应子图,完全不需要手动维护计数器、行列索引
  • 用pd.crosstab替代groupby + reset_index + pivot组合,代码更简洁可读性更高
  • 新增堆叠柱状图数据标签自动标注逻辑,解决标签显示问题

完整可运行代码

import pandas as pd
import matplotlib.pyplot as plt

# 数据集生成
d = {
    'SeniorCitizen': [0,1,0,0,0,0,0,1,0,1,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0] , 
    'CollegeDegree': [0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,1,1,1,1] , 
    'Married': [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1] , 
    'FulltimeJob': [1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,0,0,1,1,0,0,0,1] , 
    'DistancefromBranch': [7,9,14,20,21,12,22,25,9,9,9,12,13,14,16,25,27,4,14,14,20,19,15,23,2] , 
    'ReversedPayment': [0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,0,1,0,1,0,0,1,0,1,0] }
CarWash = pd.DataFrame(data = d)
categoricals = ['SeniorCitizen','CollegeDegree','Married','FulltimeJob','ReversedPayment']
numerical = ['DistancefromBranch']
CarWash[categoricals] = CarWash[categoricals].astype('category')

# 优化后的绘图逻辑
fig, axes = plt.subplots(2, 2, figsize=(15, 10))
# 展平子图数组,和分类变量一一匹配
for col, ax in zip(categoricals[:-1], axes.flat):
    # 直接生成交叉统计结果,省略冗余的格式转换步骤
    count_df = pd.crosstab(index=CarWash[col], columns=CarWash['ReversedPayment'])
    count_df.plot(kind='bar', stacked=True, ax=ax, rot=0)
    # 统一配置子图样式
    ax.set_title(f'{col}维度下目标变量分布', fontsize=12)
    ax.set_xlabel(col, fontsize=10)
    ax.set_ylabel('样本数量', fontsize=10)
    # 堆叠块添加数值标签
    for container in ax.containers:
        ax.bar_label(container, label_type='center', fontsize=9)

plt.tight_layout()
plt.show()

扩展性说明

如果后续分类变量数量变化,仅需要调整plt.subplots的行列参数即可,无需修改循环内部逻辑;如果需要统一调整图表样式、标签格式,直接修改循环内的ax配置即可,维护成本更低。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 20:36:06