迹忆客 专注技术分享

当前位置:主页 > 学无止境 > 编程语言 > Python >

在 Python Matplotlib 中添加趋势线

作者:迹忆客 最近更新:2023/03/17 浏览次数:

本篇文章将讨论在 Matplotlib 中向绘图添加趋势线。

在 Matplotlib 中生成要绘制的数据

在使用绘图之前,我们需要设置我们的脚本以使用该库。我们首先导入 Matplotlib。

我们从 random 模块加载 randrange 函数以快速生成一些数据。因此,请记住,这对你来说会有所不同。

import numpy
from matplotlib import pyplot as plt

x = [x for x in range(0, 10)]
y = numpy.random.rand(10)

在 Python Matplotlib 中使用 NumPy 添加趋势线

趋势线显示数据是增加还是减少。例如,地球上的整体温度可能看起来在波动,但它们正在上升。

我们用 NumPy 计算趋势线。为此,我们需要 x 轴和 y 轴。

然后我们使用 NumPypolyfitpoly1d 函数。最后,我们绘制趋势线。

# Plot the Data itself.
plt.plot(x, y)

# Calculate the Trendline
z = numpy.polyfit(x, y, 1)
p = numpy.poly1d(z)

# Display the Trendline
plt.plot(x, p(x))

输出:

在 Matplotlib 中添加趋势线

完整代码

import numpy
from matplotlib import pyplot as plt

x = [x for x in range(0, 10)]
y = numpy.random.rand(10)

# Plot the Data itself.
plt.plot(x, y)

# Calculate the Trendline
z = numpy.polyfit(x, y, 1)
p = numpy.poly1d(z)

# Display the Trendline
plt.plot(x, p(x))

plt.show()

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Pandas read_csv()函数

发布时间:2024/04/24 浏览次数:254 分类:Python

Pandas read_csv()函数将指定的逗号分隔值(csv)文件读取到 DataFrame 中。

Pandas 追加数据到 CSV 中

发布时间:2024/04/24 浏览次数:352 分类:Python

本教程演示了如何在追加模式下使用 to_csv()向现有的 CSV 文件添加数据。

Pandas 多列合并

发布时间:2024/04/24 浏览次数:628 分类:Python

本教程介绍了如何在 Pandas 中使用 DataFrame.merge()方法合并两个 DataFrames。

Pandas loc vs iloc

发布时间:2024/04/24 浏览次数:837 分类:Python

本教程介绍了如何使用 Python 中的 loc 和 iloc 从 Pandas DataFrame 中过滤数据。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便