如何獲取 Matplotlib生成的散點圖的畫素座標?
如需獲取 matplotlib 生成的散點圖的畫素座標,我們可以採取以下步驟 -
- 設定圖形大小並調整子圖之間和周圍的邊距。
- 初始化一個變數 “n” 來儲存樣本資料數。
- 建立一個圖形和一組子圖。
- 繪製散點圖。
- 使用 get_data() 方法獲取 x 和 y 資料點。
- 獲取繪圖的畫素值。
- 獲取畫素轉換資料。
- 以點或畫素獲取圖形寬度和高度
- 列印 x 和 y 畫素值。
- 使用 show() 方法顯示圖形。
示例
import numpy as np import matplotlib.pyplot as plt plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True n = 10 fig, ax = plt.subplots() points, = ax.plot(np.random.random(n), np.random.random(n), 'r*') x, y = points.get_data() pixels = ax.transData.transform(np.vstack([x, y]).T) x, y = pixels.T width, height = fig.canvas.get_width_height() y = height - y print("The pixel coordinates are: ") for xp, yp in zip(x, y): print('{x:0.2f}\t{y:0.2f}'.format(x=xp, y=yp)) plt.show()
輸出
將生成以下輸出
還將在控制檯中列印 matplotlib 生成的散點圖的畫素座標
The pixel coordinates are: 564.93 161.83 446.27 112.60 153.39 247.65 236.90 258.34 519.10 301.04 237.66 118.16 149.71 303.29 386.74 105.81 172.93 121.81 110.94 116.20
廣告