目标:批量输出观测值和模型预测值之间的拟合曲线
结果:

参考:
(2条消息) python绘制1:1对角线(1:1 line)_撼沧的博客-CSDN博客_python 1:1线绘制,(2条消息) 使用python来完成数据的线性拟合_布鲁斯度的博客-CSDN博客_python 线性拟合
代码
# -*- coding: utf-8 -*-
"""
批量输出观测值和模型预测值之间的拟合曲线
有R2,有拟合曲线公式,有1:1线,有图该有的要素
YMJ 20230112 22:30
"""
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from numpy import NaN
from sklearn.linear_model import LinearRegression
import matplotlib
import pandas as pd
import seaborn as sns
from matplotlib.pyplot import MultipleLocator
from pylab import mpl
# 设置字体
mpl.rcParams['font.sans-serif'] = ['SimHei']
mpl.rcParams['axes.unicode_minus'] = False
dir = 'D:\\YMJ_file\\通量数据相关\\11-model_run\\新建文件夹'
# 构造文件绝对路径
file_list = []
for root,subroot,files in os.walk(dir):
for file in files:
FM_NLS_file = os.path.join(root, file)
file_list.append(FM_NLS_file)
# 遍历文件
for i in range(len(file_list)):
data = pd.read_excel(file_list[i])
header_list = data.columns.to_list()
# LE是观测值,当作x;E是模型预测值,当作y;转为列表格式
x = data['LE'].tolist()
y = data['E'].tolist()
# subplots(1, 1)设置窗口个数,这里就一个,dpi分辨率为800
fig, ax = plt.subplots(1, 1, dpi = 800)
# 绘制1:1对角线,linewidth线的粗细,ls线的格式,c线的颜色,
ax.plot((0, 1), (0, 1), linewidth = 1, transform = ax.transAxes, ls = '--', c = 'k', label = "1:1 line")
# 绘制点,'o'点的形状,点的颜色,markersize点的大小
ax.plot(x, y, 'o', c = 'black', markersize = 5)
# polyfit(x, y, 1),1代表线性拟合
# parameter返回的是线性拟合线的斜率和截距
parameter = np.polyfit(x, y, 1)
f = np.poly1d(parameter)
ax.plot(x, f(x), 'r--', lw=1)
# 计算相关系数R
corr = np.corrcoef(x, y)[0,1]
print(corr)
# 那个框框的设置
bbox = dict(boxstyle = "round", fc = '1',alpha = 0.5)
bbox = bbox
# 在图上安放R2和拟合曲线公式,0.05和0.85是位置偏移量,自己调试
plt.text(0.05, 0.85, "$R^2=%.2f$\n$y=%.2fx+%.2f$" % ((corr**2),parameter[0], parameter[1]),
transform = ax.transAxes, size = 13,bbox = bbox)
# 横轴的设置
ax.set_xlabel('Observed LE(W/$m^2$)', fontsize = 12)
ax.set_ylabel("Predicted LE(W/$m^2$)", fontsize = 12)
# 设置图片title
ax.tick_params(labelsize = 10)
ax.set_title(file_list[i].split("\\")[-1].split(".xlsx")[0], fontsize = 10)
x_major_locator = MultipleLocator(25)
ax.xaxis.set_major_locator(x_major_locator)
y_major_locator = MultipleLocator(25)
ax.yaxis.set_major_locator(y_major_locator)
# 坐标轴
ax.set(xlim = (50,500),ylim = (50,500))
# plt.show()
outpath = os.path.join(dir, file_list[i].split("\\")[-1].split(".xlsx")[0] + ".jpg")
# 剪切至合适尺寸
plt.savefig(outpath, bbox_inches = 'tight')