Skip to contents

Mirror coordinates

Usage

CoordMirror(xy_coords, mirror.x = FALSE, mirror.y = FALSE, center = NULL)

Arguments

xy_coords

A matrix, data.frame or tbl object with numeric x, y coordinates.

mirror.x, mirror.y

Logical specifying whether the coordinates should be reflected along the x-axis, y-axis or both.

center

Optional point (x, y) specifying the center of reflection.

Value

A tbl object with transformed coordinates

Details

The coordinate system for xy_coords should match the dimensions of the image. In other words, the coordinates should map spots to the tissue section on H&E image. A 3x3 transformation matrix is constructed by combining the following matrices:

  • \(T(-x, -y)\): Translate coordinates to origin, i.e. (0, 0) becomes the new center

    10\(-center_{x}\)
    01\(-center_{y}\)
    001
  • \(M_{x}\): Reflect coordinates along x-axis

    -100
    010
    001
  • \(M_{y}\): Reflect coordinates along y-axis

    100
    0-10
    001
  • \(T(x, y)\): Translate coordinates back to center

    10\(center_{x}\)
    01\(center_{y}\)
    001

Then, these matrices are combined to form the final transformation matrix:

\(T_{final} = T(x, y)*M_{y}*M_{x}*T(-x, -y)\)

Which can be used to transform our input coordinates:

\(xy_{out} = T_{final}*xy_{in}\)

Author

Ludvig Larsson

Examples

library(ggplot2)

# Create a data.frame with x, y coordinates
xy <- data.frame(x = 1:20, y = 1:20)

# Reflect coordinates along x axis
xy_mx <- CoordMirror(xy, mirror.x = TRUE) |> setNames(nm = c("x", "y"))

# Reflect along both x, and y axes
xy_mxy <- CoordMirror(xy, mirror.x = TRUE, mirror.y = TRUE) |> setNames(nm = c("x", "y"))

# Combine all coordinates
xy_all <- do.call(rbind, list(cbind(xy, type = "original", ord = 1:20),
                    cbind(xy_mx, type = "mirror_x", ord = 1:20),
                    cbind(xy_mxy, type = "mirror_x_and_y", ord = 1:20)))
xy_all$type <- factor(xy_all$type, levels = c("original", "mirror_x", "mirror_x_and_y"))

# Now we can see the effects of mirroring
# Mirror x flips the coordinates along the x axis while mirror_x and mirror_y
# effectively inverts the coordinates, thus changing the order of the points
ggplot(xy_all, aes(x, y)) +
  geom_point(color = "steelblue", size = 7, alpha = 0.5) +
  geom_text(aes(label = ord)) +
  facet_grid(~type) +
  geom_vline(xintercept = 10.5, linetype = "dashed", color = "red") +
  geom_hline(yintercept = 10.5, linetype = "dashed", color = "green")