Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I create rectangles in ggplot with known centers, dimensions and orientations

How can I create rectangles in ggplot with known centers, dimensions and orientations

library(tidyverse)

tbl <- tibble(center_x = c(10, 50),
              center_y = c(20, 30),
              width = c(4, 7),
              length = c(8, 12),
              angle = c(120, 45), # degrees
              color = c("blue", "yellow"))

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

There is no convenient way of doing this. You’d have to reparametrise the rectangles as polygons and perform the affine transformation yourself.

library(tidyverse)

tbl <- tibble(center_x = c(10, 50),
              center_y = c(20, 30),
              width = c(4, 7),
              length = c(8, 12),
              angle = c(120, 45), # degrees
              color = c("blue", "yellow"))

poly <- tbl %>%
  mutate(
    id = seq_along(center_x),
    xmin = - 0.5 * width,
    xmax = + 0.5 * width,
    ymax = + 0.5 * length,
    ymin = - 0.5 * length,
    rads = angle / 180 * pi
  ) %>%
  pivot_longer(c("xmax", "xmin"), "xpos", values_to = "x") %>%
  pivot_longer(c("ymax", "ymin"), "ypos", values_to = "y") %>%
  group_by(id) %>%
  mutate(
    y = y[c(1, 2, 4, 3)], # prevent hourglass polygons
    xrot = x * cos(rads) - y * sin(rads),
    yrot = y * cos(rads) + x * sin(rads)
  )

ggplot(poly) +
  geom_polygon(
    aes(x = center_x + xrot,
        y = center_y + yrot,
        group = id, fill = I(color))
  ) +
  coord_equal()

Created on 2021-11-16 by the reprex package (v1.0.0)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading