使用seaborn lmplot合并多年度数据集到同一张图分色绘制的方法
实现思路
- 第一步:合并三个年度的DataFrame,新增
year字段标识所属年份 - 第二步:调用
sns.lmplot时使用hue参数指定按year字段分组着色,即可自动实现不同年份的散点、拟合线颜色区分,同时自动生成图例 - 第三步:可按需将三个模型的R²值整合到标题或图例标签中,完善图表信息
完整实现代码
import pandas as pd import seaborn as sns import matplotlib.pyplot as plt # 1. 给每个年度DataFrame添加年份标识后合并 df_2018_avg['year'] = '2018' df_2019_avg['year'] = '2019' df_2020_avg['year'] = '2020' df_all = pd.concat([df_2018_avg, df_2019_avg, df_2020_avg], ignore_index=True) # 2. 调用lmplot,用hue参数按年份区分颜色 g = sns.lmplot( x="CDD", y="kWh", data=df_all, hue="year", # 核心参数:按year字段分组着色 fit_reg=True, height=8, aspect=15/8 # 直接指定宽高比,等价于之前的fig.set_size_inches(15,8) ) # 3. 设置标题,整合三个年度的R²信息 r2_info = f"2018 R²: {round(stats_model_2018.rsquared,2)} | 2019 R²: {round(stats_model_2019.rsquared,2)} | 2020 R²: {round(stats_model_2020.rsquared,2)}" g.fig.suptitle(f'kWh / Day Vs CDD Model (2018-2020) | {r2_info}', y=1.02) # y参数调整标题位置避免被遮挡 plt.show()
可选优化
如果希望把R²值放到图例里而非标题,可以自定义图例标签,代码如下:
# 自定义图例标签,添加R²信息 handles, labels = g.get_legend_handles_labels() new_labels = [ f"2018 (R²={round(stats_model_2018.rsquared,2)})", f"2019 (R²={round(stats_model_2019.rsquared,2)})", f"2020 (R²={round(stats_model_2020.rsquared,2)})" ] g.legend.remove() # 移除默认图例 g.add_legend(handles=handles, labels=new_labels, title='Year')
内容的提问来源于stack exchange,提问作者bbartling
相关产品推荐
相关产品推荐

