R语言 如何将多个标签添加到图外的多面ggplot?

mkshixfv  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(116)

我使用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)

bqjvbblv

bqjvbblv1#

一种选择是使用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")

字符串


的数据

相关问题