dba
dba

Reputation: 345

convert pixel-coordinates to data-coordinates

I am creating a plot with matplotlib.pyplot. For this image I need a function that maps pixel-coordinates to the coordinates of the data (for interaction with the user in another GUI-system outside of python). I have tried the function ax.transData.inverted().transform(x), since it maps display-coordinates to data-coordinates. But the numbers that I get have an offset of roughly 23 pixels in x-direction. I went through this tutorial, but I could not find anything on this problem.

I have also tried this code from stackoverflow, where the printed x-coordinates have an offset of 25 pixels. I could see that Maybe the area left to the y-axis is not included there? I definitely need it to be included. In the attached picture I am comparing what the code from stackoverflow yields vs what MS paint tells me about the x-coordinate of the red dot. They are not the same.

Datapoints from the code example

Upvotes: 2

Views: 6683

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339120

As commented, ax.transData.inverted().transform(x) does indeed give you the data coordinates of x defined in pixels.

So we run

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
points, = ax.plot(range(10), 'ro')
ax.axis([-1, 10, -1, 10])
fig.savefig("test.png")

open the saved picture in Irfanview and mark the dot at (0,0).

enter image description here

As seen in the image, it's at (126, 86) pixels. So plugging in this tuple

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
points, = ax.plot(range(10), 'ro')
ax.axis([-1, 10, -1, 10])

x = 126, 86
point = ax.transData.inverted().transform(x)
print(point)

We get

[ 0.02016129 -0.01190476]

which is as close to (0,0) as you can get, given that the pixel resolution is

x2 = 125, 85
point2 = ax.transData.inverted().transform(x2)
print(point - point2)

[0.02217742 0.0297619 ]

and hence larger than those obtained numbers.

This might arguably not answer the question, but it is all one can possibly say here, with the information from the question at hand.

Upvotes: 2

Related Questions