Home > front end >  Pixel coordinates of matplotlib scatter plot
Pixel coordinates of matplotlib scatter plot

Time:11-12

I am referencing this post and implementing the solution, however I am getting very large values. Thanks for any help, attached it the code.

import numpy as np
import matplotlib.pyplot as plt

x_labels = ['x1','x2','x3']
y_values = [30,40,50]

coordList = []
x_vals = []
i = 0
fig, ax = plt.subplots()
for item in x_labels:
    x_vals.append(i)
    i =1
points, = ax.plot(x_vals, y_values)
x, y = points.get_data()
print(x, y)
xy_pixels = ax.transData.transform(np.vstack([x,y]).T)
xpix, ypix = xy_pixels.T
for xp, yp in zip(xpix, ypix):
    coordList.append(f'{xp}, {yp}')
print(coordList)

Here is a resulting coordList:

['80.0, 39969.6', '576.0, 37382.4', '1072.0, 34425.6', '1568.0, 31838.399999999998', '2064.0, 29620.799999999996', '2560.0, 26663.999999999996', '3056.0, 24815.999999999996', '3552.0, 21859.199999999997', '4048.0, 19271.999999999996']

CodePudding user response:

What you see is the original transformation prior to the internal automatic setting of the axes bounds. In order to force an update of the transformation, you need to either get the bounds by e.g get_xbounds() or completely update the figure first by calling fig.canvas.draw() (in the linked example the update was ensured by ax.axis([-1, 10, -1, 10])).

ax.get_xbound()
xy_pixels = ax.transData.transform(np.vstack([x,y]).T)

Result (for my display):

[0 1 2] [30 40 50]
['102.54545454545455, 69.59999999999997', '328.0, 237.59999999999997', '553.4545454545454, 405.59999999999997']

source

  • Related