如何在 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='line plot')
y_avg = [np.mean(x)] * len(x)
ax.plot(x, y_avg, color='red', lw=6, ls='--', label="average plot")

plt.legend(loc=0)
plt.show()

輸出

更新於: 2021 年 6 月 3

3k+ 瀏覽

職業啟航

透過完成課程獲得認證

開始
廣告
© . All rights reserved.