如何获取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("像素坐标是:")
for xp, yp in zip(x, y):
print('{x:0.2f}\t{y:0.2f}'.format(x=xp, y=yp))
plt.show()
结果
它将产生以下输出
它还将在控制台上显示Matplotlib生成的散点图的像素坐标。
像素坐标是:
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