
❝2月底ggplot2更新了最新版3.5,本节来介绍一下ggplot2 3.5版更新的内容之「图例操作部分」,使用最新版后定义图例位置将变得异常的简单,更多详细内容请参考作者官方文档。 ❞
install.packages("ggplot2") # 需要安装ggplot2 3.5
library(ggplot2)
https://www.tidyverse.org/blog/2024/02/ggplot2-3-5-0-legends/
ggplot(mpg, aes(displ, hwy, shape = drv, colour = cty, size = year)) +
  geom_point(aes(alpha = cyl)) +
  guides(
    colour = guide_colourbar(position = "bottom"),
    size   = guide_legend(position = "top"),
    alpha  = guide_legend(position = "inside")) +
  theme(legend.position = "left")

ggplot(mpg, aes(displ, hwy,colour = cty, shape = drv)) +
  geom_point() +
  guides(
    colour = guide_colourbar(position = "right"),
    shape   = guide_legend(position = "top"))+
  theme(legend.key.height = unit(1, "null"),
        legend.justification.top = "right")

x <- c(0.5, 1, 1.5, 1.2, 1.5, 1, 0.5, 0.8, 1, 1.15, 2, 1.15, 1, 0.85, 0, 0.85)
y <- c(1.5, 1.2, 1.5, 1, 0.5, 0.8, 0.5, 1, 2, 1.15, 1, 0.85, 0, 0.85, 1, 1.15)
compass_rose <- grid::polygonGrob(
  x = unit(x, "cm"), y = unit(y, "cm"), id.lengths = c(8, 8),
  gp = grid::gpar(fill = c("grey50", "grey25"), col = NA)
)
nc <- sf::st_read(system.file("shape/nc.shp", package = "sf"), quiet = TRUE)
ggplot(nc) +
  geom_sf(aes(fill = AREA)) +
  guides(custom = guide_custom(compass_rose, title = "compass"))
