如何從 Matplotlib 圖表中提取資料?


如要從 Matplotlib 中的圖表提取資料,我們可使用 get_xdata()get_ydata() 方法。

步驟

  • 設定圖形大小並調整子圖之間和周圍的邊距。
  • 使用 numpy 建立 y 資料點。
  • 使用 color=redlinewidth=5 繪製 y 資料點。
  • 列印用於資料提取的語句。
  • 使用 get_xdata()get_ydata() 方法從圖表提取資料(步驟 3)。
  • 列印 x 和 y 資料(步驟 5)。
  • 如要顯示圖表,請使用 show() 方法。

示例

import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
y = np.array([1, 3, 2, 5, 2, 3, 1])
curve, = plt.plot(y, c='red', lw=5)
print("Extracting data from plot....")
xdata = curve.get_xdata()
ydata = curve.get_ydata()
print("X data points for the plot is: ", xdata)
print("Y data points for the plot is: ", ydata)
plt.show()

輸出

Extracting data from plot....
X data points for the plot is: [0. 1. 2. 3. 4. 5. 6.]
Y data points for the plot is: [1 3 2 5 2 3 1]

更新於: 2021 年 6 月 1 日

14,000+ 次瀏覽

啟動你的 職業生涯

完成課程並獲得認證

開始
廣告
© . All rights reserved.