Home > Net >  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

Time:11-17

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"))

CodePudding user response:

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)

  • Related