如何用迭代方式为不同ID生成重叠子图(Python)
用迭代逻辑实现多ID重叠子图绘制
核心思路是通过配置化管理数据源+双层迭代,避免重复编写子图代码。以下是具体实现:
步骤1:准备示例数据(模拟你的df_1和df_2)
import pandas as pd import matplotlib.pyplot as plt # 模拟业务数据 df_1 = pd.DataFrame({ 'ID': ['A', 'A', 'B', 'B', 'C', 'C', 'D', 'D'], 'cycle_1': [1, 2, 1, 2, 1, 2, 1, 2], 'Salary_1': [5000, 6000, 7000, 8000, 9000, 10000, 11000, 12000] }) df_2 = pd.DataFrame({ 'ID': ['A', 'A', 'B', 'B', 'C', 'C', 'D', 'D'], 'cycle_2': [1, 2, 1, 2, 1, 2, 1, 2], 'Salary_2': [5500, 6500, 7500, 8500, 9500, 10500, 11500, 12500] })
步骤2:迭代绘制子图
# 定义数据源配置:每个元素包含(数据框, cycle列名, salary列名, 图例标签) data_configs = [ (df_1, 'cycle_1', 'Salary_1', 'Cycle 1 vs Salary 1'), (df_2, 'cycle_2', 'Salary_2', 'Cycle 2 vs Salary 2') ] # 获取所有需绘制的唯一ID(取两个df的交集,避免ID缺失) unique_ids = list(set(df_1['ID']) & set(df_2['ID'])) total_ids = len(unique_ids) # 创建子图布局(这里用2行2列适配4个ID) fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(12, 8)) axes = axes.flatten() # 将二维子图数组转为一维,方便迭代 # 外层迭代:遍历每个ID和对应的子图 for idx, target_id in enumerate(unique_ids): current_ax = axes[idx] # 内层迭代:遍历所有数据源,在当前子图绘制曲线 for df, cycle_col, salary_col, label in data_configs: # 筛选当前ID的数据 id_data = df[df['ID'] == target_id] # 绘制折线图(可根据需求调整样式) current_ax.plot(id_data[cycle_col], id_data[salary_col], marker='s', linewidth=2, label=label) # 设置子图基础属性 current_ax.set_title(f'ID: {target_id}', fontweight='bold') current_ax.set_xlabel('Cycle') current_ax.set_ylabel('Salary') current_ax.legend() current_ax.grid(alpha=0.3) # 自动调整子图间距,避免标签重叠 plt.tight_layout() plt.show()
关键优势
- 可扩展性:后续新增数据源或ID时,只需修改
data_configs或调整子图布局,无需重复编写绘图逻辑 - 代码简洁:通过两层迭代替代四次重复的subplot代码
- 一致性:所有子图的样式、标签规则统一,避免手动编写时的不一致问题
内容的提问来源于stack exchange,提问作者NN_Developer
相关产品推荐
相关产品推荐

