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')
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值