使用Seaborn循环绘制DataFrame分组折线子图遇重复结果求助
问题解决:Seaborn折线子图重复及需求实现
问题根源
你的代码没有按当前Center筛选数据,每次循环都调用全量的df_test,且sns.lineplot的data参数错误传入了Center值(col),导致所有子图都显示全量数据,结果完全重复。
需求1:按Center分别展示Cost和Cost Factor变化
修正后代码
import pandas as pd import matplotlib.pyplot as plt import seaborn as sns # 转换日期格式,保证x轴按时间顺序排列 df_test['Month Start'] = pd.to_datetime(df_test['Month Start']) centers = df_test['Center'].unique() # 根据Center数量创建子图 fig, axes = plt.subplots(nrows=len(centers), ncols=1, figsize=(20, 12)) for i, center in enumerate(centers): # 筛选当前Center的专属数据 center_data = df_test[df_test['Center'] == center] # 绘制Cost折线 sns.lineplot(x='Month Start', y='Cost', data=center_data, ax=axes[i], label='Cost') # 绘制Cost Factor折线 sns.lineplot(x='Month Start', y='Cost FACTOR', data=center_data, ax=axes[i], label='Cost Factor') # 设置子图标题与图例 axes[i].set_title(f'Center {center}: Cost & Cost Factor Trend') axes[i].legend() plt.tight_layout() plt.show()
关键修正点
- 新增日期格式转换,避免x轴时间顺序混乱
- 循环时通过条件筛选获取当前Center的专属数据
- 正确传递
data参数为筛选后的DataFrame,直接指定x、y列名(符合Seaborn最佳实践) - 为每条折线单独设置
label,自动生成准确图例
需求2:按Center+State组合展示变化
实现代码
import pandas as pd import matplotlib.pyplot as plt import seaborn as sns df_test['Month Start'] = pd.to_datetime(df_test['Month Start']) # 获取所有Center+State的唯一组合 center_state_pairs = df_test[['Center', 'State']].drop_duplicates().values.tolist() # 根据组合数量自动创建子图 fig, axes = plt.subplots(nrows=len(center_state_pairs), ncols=1, figsize=(20, 5*len(center_state_pairs))) for i, (center, state) in enumerate(center_state_pairs): # 筛选当前Center+State组合的专属数据 combo_data = df_test[(df_test['Center'] == center) & (df_test['State'] == state)] sns.lineplot(x='Month Start', y='Cost', data=combo_data, ax=axes[i], label='Cost') sns.lineplot(x='Month Start', y='Cost FACTOR', data=combo_data, ax=axes[i], label='Cost Factor') axes[i].set_title(f'Center {center} - State {state}: Cost & Cost Factor Trend') axes[i].legend() plt.tight_layout() plt.show()
说明
- 通过
drop_duplicates()获取所有唯一的Center-State组合,无需手动指定数量 - 用多条件筛选获取组合专属数据
- 子图行数自动适配组合数量,提升代码灵活性
内容的提问来源于stack exchange,提问作者user21359260
相关产品推荐
相关产品推荐

