如何在MatPlotLib中绘制散点图的平均线?
要在matplotlib中绘制图的平均线,我们可以按照以下步骤进行−
- 设置图像大小并调整子图之间和周围的填充。
-
使用numpy创建x和y数据点。
-
使用subplots()方法创建一个图像和一组子图。
-
对x和y数据点使用plot()方法。
-
找到数组x的平均值。
-
使用plot()方法绘制x和y_avg数据点。
-
在图像上放置一个图例。
-
使用show()方法显示图像。
示例
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
x = np.array([3, 4, 5, 6, 7, 8, 9])
y = np.array([6, 5, 4, 3, 2, 1, 6])
fig, ax = plt.subplots()
ax.plot(x, y, 'o-', label='线性图')
y_avg = [np.mean(x)] * len(x)
ax.plot(x, y_avg, color='red', lw=6, ls='--', label="平均线性图")
plt.legend(loc=0)
plt.show()