如何在 ggplot 中創建具有已知中心、尺寸和方向的矩形
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"))
uj5u.com熱心網友回復:
沒有方便的方法來做到這一點。您必須將矩形重新引數化為多邊形并自己執行仿射變換。
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()

由reprex 包(v1.0.0)于 2021 年 11 月 16 日創建
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/358127.html
