如何在绘图之外向多面ggplot添加多个标签?

问题描述 投票:0回答:1

我使用facet_rep_grid来可视化同一x轴上的不同变量。现在我想用“A”,“B”,“C”等标记每个面的左上角。

我所拥有的看起来与此类似,但单个面之间的 y 轴差异更大:

library(dplyr)
library(ggplot2)
library(ggthemes)
library(lemon)
library(grid)
library(cowplot) 

# mpg dataset from ggplot2

mylabs <- c("facet 1", " facet 2", 'facet 3', 'facet 4')
names(mylabs) <- c(4,5,6,8)

ggplot(mpg,aes(x=year, y=hwy)) + 
  geom_point()+
  facet_rep_grid(cyl~., switch='y', scales="free", labeller=labeller(cyl=mylabs))+
  theme(strip.placement = "outside",
        strip.background = element_blank(),
        axis.title.y = element_blank())


我想要的是:

image

我尝试调整this,这仅对“A”有好处。

ggplot(mpg,aes(x=year, y=hwy)) + 
  geom_point()+
  facet_rep_grid(cyl~., switch='y', scales="free", labeller=labeller(cyl=mylabs))+
  theme(strip.placement = "outside",
        strip.background = element_blank(),
        axis.title.y = element_blank())+
  
        labs(tag = "A/ only one") +
        coord_cartesian(clip = "off")

我还发现了this,但我无法将标签移到绘图之外。

ggplot(mpg,aes(x=year, y=hwy)) + 
  geom_point()+
  facet_rep_grid(cyl~., switch='y', scales="free", labeller=labeller(cyl=mylabs))+
  theme(strip.placement = "outside",
        strip.background = element_blank(),
        axis.title.y = element_blank())+

  coord_cartesian(clip = "off")+
  geom_text(data = myLab, aes(x = -500, y = 10, label = mylabs), hjust =0) 
r ggplot2 facet-grid geom-text annotate
1个回答
0
投票

一种选择是使用

patchwork
,即通过单独的图表创建绘图。之后您可以通过
plot_annotation
轻松添加标签。

library(ggplot2)
#> Warning: package 'ggplot2' was built under R version 4.2.3
library(patchwork)
#> Warning: package 'patchwork' was built under R version 4.3.1

mylabs <- c("facet 1", " facet 2", "facet 3", "facet 4")
names(mylabs) <- c(4, 5, 6, 8)

myfun <- function(.data, cyl) {
  remove_x <- if (cyl != "8") {
    theme(
      axis.title.x = element_blank(),
      axis.text.x = element_blank()
    )
  }
  ggplot(.data, aes(x = year, y = hwy)) +
    geom_point() +
    scale_x_continuous(limits = range(mpg$year)) +
    facet_grid(cyl ~ .,
      switch = "y", scales = "free_y",
      labeller = labeller(cyl = mylabs)
    ) +
    theme(
      strip.placement = "outside",
      strip.background = element_blank(),
      axis.title.y = element_blank(),
      plot.margin = margin()
    ) +
    remove_x
}

mpg |>
  split(~cyl) |>
  purrr::imap(
    myfun
  ) |>
  wrap_plots(ncol = 1) &
  plot_annotation(tag_levels = "A")

© www.soinside.com 2019 - 2024. All rights reserved.