Python实现线性拟合及绘图的示例代码

 更新时间:2024年04月28日 14:42:20   作者:浩瀚地学  
在数据处理和绘图中,我们通常会遇到直线或曲线的拟合问题,本文主要介绍了Python实现线性拟合及绘图的示例代码,具有一定的参考价值,感兴趣的可以了解一下

当时的数字地形实验,使用 matplotlib库绘制了一张图表表示不同地形类别在不同分辨率下的RMSE值,并分别拟合了一条趋势线。现在来看不足就是地形较多时,需要使用循环更好一点,不然太冗余了。

环境:Python 3.9

代码逻辑

导入所需库以及初步设置

# coding=gbk
# -*- coding = utf-8 -*-

import matplotlib.pyplot as plt
import numpy as np
plt.subplots_adjust(left=0.05, right=0.7, top=0.9, bottom=0.1)
plt.rcParams['font.sans-serif'] = ['SimHei']

准备数据(这里仅展示部分)

resolutions = [50, 100, 150, 200, 250]
plain = [0, 0, 1, 1, 1]
hill = [2.645751311, 7.071067812, 10.44030651, 11.48912529, 14.4222051]

这里可以改为在Excel中读取,尤其是数据多的时候

分别绘制不同数据的趋势线

# 绘制平原趋势线
coefficients_plain = np.polyfit(resolutions, plain, 1)
poly_plain = np.poly1d(coefficients_plain)
plt.plot(resolutions, plain, '^', label="平原")
plt.plot(resolutions, poly_plain(resolutions), label="平原趋势线")

# 绘制丘陵趋势线
coefficients_hill = np.polyfit(resolutions, hill, 1)
poly_hill = np.poly1d(coefficients_hill)
plt.plot(resolutions, hill, '^', label="丘陵")
plt.plot(resolutions, poly_hill(resolutions), label="丘陵趋势线")

使用np.polyfit函数拟合一阶多项式(直线),然后使用np.poly1d构造多项式对象。绘制原始数据点(用’^'标记)和对应的拟合趋势线。

计算指标

# 计算平原趋势线的r值和r方
residuals_plain = plain - poly_plain(resolutions)
ss_residuals_plain = np.sum(residuals_plain**2)
ss_total_plain = np.sum((plain - np.mean(plain))**2)
r_squared_plain = 1 - (ss_residuals_plain / ss_total_plain)
r_plain = np.sqrt(r_squared_plain)

# 计算丘陵趋势线的r值和r方
residuals_hill = hill - poly_hill(resolutions)
ss_residuals_hill = np.sum(residuals_hill**2)
ss_total_hill = np.sum((hill - np.mean(hill))**2)
r_squared_hill = 1 - (ss_residuals_hill / ss_total_hill)
r_hill = np.sqrt(r_squared_hill)

计算得到r方和r值

绘图和打印指标

# 设置图例和标题
plt.legend()
plt.legend(loc='center left', bbox_to_anchor=(1.05, 0.5))
plt.title("地形趋势线")

# 设置坐标轴标题
new_ticks = np.arange(50, 251, 50)
plt.xticks(new_ticks)
plt.xlabel('分辨率(m)')
plt.ylabel('RMSE')
formula1 = "平原:{}".format(poly_plain)
plt.text(0.05, 0.95, formula1, transform=plt.gca().transAxes,
         fontsize=10, verticalalignment='top')
formula1 = "丘陵:{}".format(poly_hill)
plt.text(0.35, 0.95, formula1, transform=plt.gca().transAxes,
         fontsize=10, verticalalignment='top')

# 显示图形
plt.figure(figsize=(10, 10))
plt.show()

# 打印
print("平原趋势线公式:", poly_plain)
print("丘陵趋势线公式:", poly_hill)
print("平原趋势线:")
print("r值:", r_plain)
print("r方:", r_squared_plain)
print()
print("丘陵趋势线:")
print("r值:", r_hill)
print("r方:", r_squared_hill)
print()

完整代码

# coding=gbk
# -*- coding = utf-8 -*-

import matplotlib.pyplot as plt
import numpy as np
plt.subplots_adjust(left=0.05, right=0.7, top=0.9, bottom=0.1)
plt.rcParams['font.sans-serif'] = ['SimHei']

resolutions = [50, 100, 150, 200, 250]
plain = [0, 0, 1, 1, 1]
hill = [2.645751311, 7.071067812, 10.44030651, 11.48912529, 14.4222051]

# 绘制平原趋势线
coefficients_plain = np.polyfit(resolutions, plain, 1)
poly_plain = np.poly1d(coefficients_plain)
plt.plot(resolutions, plain, '^', label="平原")
plt.plot(resolutions, poly_plain(resolutions), label="平原趋势线")

# 绘制丘陵趋势线
coefficients_hill = np.polyfit(resolutions, hill, 1)
poly_hill = np.poly1d(coefficients_hill)
plt.plot(resolutions, hill, '^', label="丘陵")
plt.plot(resolutions, poly_hill(resolutions), label="丘陵趋势线")

# 计算平原趋势线的r值和r方
residuals_plain = plain - poly_plain(resolutions)
ss_residuals_plain = np.sum(residuals_plain**2)
ss_total_plain = np.sum((plain - np.mean(plain))**2)
r_squared_plain = 1 - (ss_residuals_plain / ss_total_plain)
r_plain = np.sqrt(r_squared_plain)

# 计算丘陵趋势线的r值和r方
residuals_hill = hill - poly_hill(resolutions)
ss_residuals_hill = np.sum(residuals_hill**2)
ss_total_hill = np.sum((hill - np.mean(hill))**2)
r_squared_hill = 1 - (ss_residuals_hill / ss_total_hill)
r_hill = np.sqrt(r_squared_hill)

# 设置图例和标题
plt.legend()
plt.legend(loc='center left', bbox_to_anchor=(1.05, 0.5))
plt.title("地形趋势线")

# 设置坐标轴标题
new_ticks = np.arange(50, 251, 50)
plt.xticks(new_ticks)
plt.xlabel('分辨率(m)')
plt.ylabel('RMSE')
formula1 = "平原:{}".format(poly_plain)
plt.text(0.05, 0.95, formula1, transform=plt.gca().transAxes,
         fontsize=10, verticalalignment='top')
formula1 = "丘陵:{}".format(poly_hill)
plt.text(0.35, 0.95, formula1, transform=plt.gca().transAxes,
         fontsize=10, verticalalignment='top')

# 显示图形
plt.figure(figsize=(10, 10))
plt.show()

# 打印
print("平原趋势线公式:", poly_plain)
print("丘陵趋势线公式:", poly_hill)
print("平原趋势线:")
print("r值:", r_plain)
print("r方:", r_squared_plain)
print()
print("丘陵趋势线:")
print("r值:", r_hill)
print("r方:", r_squared_hill)
print()

结果

在这里插入图片描述

参考

Matplotlib pyplot文档

到此这篇关于Python实现线性拟合及绘图的示例代码的文章就介绍到这了,更多相关Python 线性拟合及绘图内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Python与Node.js之间实现通信的JSON数据接收发送

    Python与Node.js之间实现通信的JSON数据接收发送

    Python和Node.js是两个流行且功能强大的编程语言,它们之间使用JSON格式进行数据交换是一种高效和灵活的方式,本文将详细介绍如何在Python和Node.js之间通过JSON进行数据通信,包括发送和接收JSON数据以及一些常见的交互示例代码
    2024-01-01
  • 深入剖析Python的列表和元组

    深入剖析Python的列表和元组

    这篇文章主要介绍了深入剖析Python的列表和元组,Python有4个内建的数据结构,它们可以统称为容器,因为它们实际上是一些“东西”组合而成的结构,而这些“东西”,可以是数字、字符甚至列表,或是它们的组合,需要的朋友可以参考下
    2023-07-07
  • Python的string模块中的Template类字符串模板用法

    Python的string模块中的Template类字符串模板用法

    通过string.Template我们可以为Python定制字符串的替换标准,这里我们就来通过示例解析Python的string模块中的Template类字符串模板用法:
    2016-06-06
  • Python使用PIL打开图片后对图片重命名报错的解决方案

    Python使用PIL打开图片后对图片重命名报错的解决方案

    在Windows系统中,当文件被某个进程占用时,其他进程无法修改/重命名该文件,使用PIL打开图片后,确实需要显式关闭图片对象以释放文件句柄,本文给大家介绍了详细的解决方案,需要的朋友可以参考下
    2026-01-01
  • 详细介绍在pandas中创建category类型数据的几种方法

    详细介绍在pandas中创建category类型数据的几种方法

    这篇文章主要介绍了详细介绍在pandas中创建category类型数据的几种方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-04-04
  • python通过zlib实现压缩与解压字符串的方法

    python通过zlib实现压缩与解压字符串的方法

    这篇文章主要介绍了python通过zlib实现压缩与解压字符串的方法,较为详细的介绍了zlib的用法及使用zlib.compressobj和zlib.decompressobj对文件进行压缩解压的方法,需要的朋友可以参考下
    2014-11-11
  • pyinstaller打包路径的总结

    pyinstaller打包路径的总结

    本文主要介绍了pyinstaller打包路径的总结,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2024-08-08
  • python 利用文件锁单例执行脚本的方法

    python 利用文件锁单例执行脚本的方法

    今天小编就为大家分享一篇python 利用文件锁单例执行脚本的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2019-02-02
  • 使用PyQt实现简易文本编辑器

    使用PyQt实现简易文本编辑器

    这篇文章主要为大家详细介绍了如何使用PyQt5框架构建一个简单的文本编辑器,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下
    2025-02-02
  • Python使用lxml库和Xpath提取网页数据的完整指南与最佳实战

    Python使用lxml库和Xpath提取网页数据的完整指南与最佳实战

    本文介绍使用Python的lxml库和Xpath提取网页数据,涵盖lxml库基础用法、代码实战,还提及处理动态加载和命名空间等进阶用法,同时阐述了爬虫的错误处理、数据存储、部署、监控等内容,以及后续的数据处理、分析、可视化和报告撰写等步骤,需要的朋友可以参考下
    2025-11-11

最新评论