Python | 使用Matplotlib绘制散点趋势线

Matplotlib是一个用于数据可视化的强大Python库,其基本功能之一是创建带有趋势线的散点图。散点图对于可视化变量之间的关系非常有用,添加趋势线有助于突出数据中的潜在模式或趋势。本文将指导您使用Matplotlib绘制散点趋势线的过程,涵盖线性和多项式趋势线。

Matplotlib绘制散点趋势线

散点图是一种数据可视化,它使用点来表示两个不同变量的值。水平轴和垂直轴上每个点的位置表示单个数据点的值。散点图用于观察变量之间的关系。

1.创建基本散点图

让我们从创建一个基本的散点图开始。为了简单起见,我们将使用随机数据。

python 复制代码
import matplotlib.pyplot as plt
import numpy as np

x = np.random.rand(50)
y = np.random.rand(50)

plt.scatter(x, y)
plt.title("Basic Scatter Plot")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.show()

2.添加线性趋势线

线性趋势线是最能代表散点图上数据的直线。要添加线性趋势线,我们可以使用NumPy的polyfit()函数来计算最佳拟合线。

python 复制代码
# Calculate the best-fit line
z = np.polyfit(x, y, 1)
p = np.poly1d(z)

# Plot the scatter plot and the trend line
plt.scatter(x, y)
plt.plot(x, p(x), "r--")  # 'r--' is for a red dashed line
plt.title("Scatter Plot with Linear Trend Line")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.show()


3.添加多项式趋势线

有时,线性趋势线可能不足以捕捉变量之间的关系。在这种情况下,多项式趋势线可能更合适。我们可以使用polyfit()函数,它的阶数更高。

python 复制代码
# Calculate the polynomial trend line (degree 2)
z = np.polyfit(x, y, 2)
p = np.poly1d(z)

# Plot the scatter plot and the polynomial trend line
plt.scatter(x, y)
plt.plot(x, p(x), "g-")  # 'g-' is for a green solid line
plt.title("Scatter Plot with Polynomial Trend Line")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.show()

自定义趋势线

Matplotlib允许对图进行广泛的自定义,包括趋势线的外观。您可以修改趋势线的颜色、线型和宽度。

python 复制代码
# Calculate the best-fit line
z = np.polyfit(x, y, 1)
p = np.poly1d(z)

# Plot the scatter plot and the customized trend line
plt.scatter(x, y)
plt.plot(x, p(x), color="purple", linewidth=2, linestyle="--")
plt.title("Scatter Plot with Customized Trend Line")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.show()

多条趋势线

在某些情况下,您可能希望比较同一散点图上的不同趋势线。这可以通过计算和绘制多条趋势线来实现。

python 复制代码
# Generate random data
x = np.random.rand(50)
y = np.random.rand(50)

# Calculate the linear and polynomial trend lines
z1 = np.polyfit(x, y, 1)
p1 = np.poly1d(z1)
z2 = np.polyfit(x, y, 2)
p2 = np.poly1d(z2)

# Plot the scatter plot and both trend lines
plt.scatter(x, y)
plt.plot(x, p1(x), "r--", label="Linear Trend Line")
plt.plot(x, p2(x), "g-", label="Polynomial Trend Line")
plt.title("Scatter Plot with Multiple Trend Lines")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.legend()
plt.show()

总结

在Matplotlib中向散点图添加趋势线是可视化和理解变量之间关系的强大方法。无论您需要简单的线性趋势线还是更复杂的多项式趋势线,Matplotlib都提供了创建信息丰富且视觉上吸引人的图表所需的工具。

相关推荐
烛阴4 小时前
简单入门Python装饰器
前端·python
好开心啊没烦恼5 小时前
Python 数据分析:numpy,说人话,说说数组维度。听故事学知识点怎么这么容易?
开发语言·人工智能·python·数据挖掘·数据分析·numpy
面朝大海,春不暖,花不开5 小时前
使用 Python 实现 ETL 流程:从文本文件提取到数据处理的全面指南
python·etl·原型模式
2301_805054566 小时前
Python训练营打卡Day59(2025.7.3)
开发语言·python
万千思绪7 小时前
【PyCharm 2025.1.2配置debug】
ide·python·pycharm
微风粼粼8 小时前
程序员在线接单
java·jvm·后端·python·eclipse·tomcat·dubbo
云天徽上8 小时前
【PaddleOCR】OCR表格识别数据集介绍,包含PubTabNet、好未来表格识别、WTW中文场景表格等数据,持续更新中......
python·ocr·文字识别·表格识别·paddleocr·pp-ocrv5
你怎么知道我是队长9 小时前
python-input内置函数
开发语言·python
叹一曲当时只道是寻常9 小时前
Python实现优雅的目录结构打印工具
python
hbwhmama10 小时前
python高级变量XIII
python