如何使用 Matplotlib 繪製散點趨勢線?


要使用 matplotlib 繪製散點趨勢線,我們可以使用 polyfit()poly1d() 方法來獲取趨勢線點。

步驟

  • 設定圖形大小並調整子圖之間的內邊距和周圍的內邊距。

  • 使用 numpy 建立 x 和 y 資料點。

  • 建立一個圖形和一組子圖。

  • 使用 numpy 繪製 x 和 y 資料點。

  • 使用 polyfit()poly1d() 方法查詢趨勢線資料點。

  • 使用 plot() 方法繪製 x 和 p(x) 資料點。

  • 要顯示圖形,請使用 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.random.rand(100)
y = np.random.rand(100)
fig, ax = plt.subplots()
_ = ax.scatter(x, y, c=x, cmap='plasma')
z = np.polyfit(x, y, 1)
p = np.poly1d(z)
plt.plot(x, p(x), "r-o")

plt.show()

輸出

更新於: 04-Jun-2021

6K+ 瀏覽量

啟動你的 職業生涯

完成課程以獲得認證

立即開始
廣告