Search code examples
c++allegro5cartesian-coordinates

Translating axes while changing bounds


So I understand to translate:

x = x' + x0     or     x' = x - x0
y = y' + y0     or     y' = y - y0

where (x,y) are old coordinates relative to xy system, (x',y') are new coordinates relative to x'y' system, and (x0,y0) are coordinates relative to old xy system.

I'm looking to translate a system while also changing the bounds. I want to "zoom in" on a particular section of a graph within a fixed window, which would change the origin and the bounds.

For reference, I asked a similar question here, but I think it was a little more confusing.


Solution

  • Hopefully this answers your question:

    Let's assume the window that you are plotting at (in pixel coordinate) is such that the lower-left corner is (p_ll, q_ll) and the upper-right corner is (p_ur, q_ur).

    In your Cartesian coordinate, however, the same locations are (x_ll, y_ll) and (x_ur, y_ur). Then these are the transformations you need:

    p(x) = p_ll + (p_ur - p_ll) * (x - x_ll) / (x_ur - x_ll)
    q(y) = q_ll + (q_ur - q_ll) * (y - y_ll) / (y_ur - y_ll)
    

    So, for example, in case that the window is x from 0 to 600 and y from 0 to 600, and the plot bounds are x from -2 to 2 and y from -1 to 1 then a point that has a coordinate of (0.0, 0.0) is going to be at (p(0), q(0)) or

    p(0.0) = 0 + (600 - 0) * (0 -(-2)) / (2 - (-2)) = 300
    q(0.0) = 600 + (0 - 600) * (0 - (-1)) / (1 - (-1)) = 300
    

    same for any other point. You can try the equation and you should find that p(-2) = 0, p(2) = 600, q(-1) = 600, and q(1) = 0.

    Note that I'm here assuming pixel y coordinate is pointing down (as almost all monitor coordinates do) while the Cartesian coordinate y is pointing up.

    If you want to go from screen coordinate to plot coordinate (for example if you want to convert the position of a mouse click to its Cartesian counter-part) then use these inverse transformations:

    x(p) = x_ll + (x_ur - x_ll) * (p - p_ll) / (p_ur - p_ll)
    y(q) = y_ll + (y_ur - y_ll) * (q - q_ll) / (q_ur - q_ll)