注释多面GGplot

时间:2019-10-16 12:47:21

标签: r ggplot2 annotations facet

示例代码

library(ggplot2)

# Base Plot
g <- ggplot(mpg, aes(x=displ, y=hwy)) + 
  geom_point() + 
  geom_smooth(method="lm", se=FALSE) + 
  theme_bw()  # apply bw theme

g + facet_wrap( ~ class, scales = "free") + labs(title="hwy vs displ", caption = "Source: mpg", subtitle="Ggplot2 - Faceting - Multiple plots in one figure with free scales")

期望的输出 enter image description here

我的目标是在多面GGPlot中的指定行中添加文本“ Group A”和“ Group B”。我已经看到了如何在每个图的内部进行此操作,但是是否可以像上面的图形示例一样在外部进行注释?

1 个答案:

答案 0 :(得分:0)

使用软件包ggpubr

library(ggpubr)

# Simulating groups
mpg$Group <- "A"
mpg[mpg$class %in% unique(mpg$class)[1:3], "Group"] <- "B"


# Generating plots by group
for (grp in unique(mpg$Group)) {
  assign(paste0("plot", grp),
    ggplot(subset(mpg, Group == grp), aes(displ, hwy)) + 
      geom_point() + 
      geom_smooth(method = "lm", se = FALSE) + 
      scale_y_continuous(position = "righ") +
      theme_bw() +
      facet_wrap(~ class, nrow = 1, scales = "free")
  )
}

# Arranging plots with annotation
ggarrange(annotate_figure(plotA, left = "Group A"),
          annotate_figure(plotB, left = "Group B"),
          nrow = 2, align = "h")

enter image description here

还要在ggarrange中选中选项labels = "AUTO"