Để trích xuất dữ liệu từ biểu đồ trong Matplotlib, ta dùng phương thức get_xdata() và get_ydata().
Các bước thực hiện
- Thiết lập kích thước hình và khoảng đệm.
- Tạo dữ liệu y bằng NumPy.
- Vẽ y với color=red, linewidth=5.
- In thông báo trích xuất.
- Dùng get_xdata(), get_ydata() lấy dữ liệu.
- In x, y data.
- Hiển thị bằng show().
Ví dụ
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()
Kết quả
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]
