Аннотировать граненый GGplot - PullRequest
       21

Аннотировать граненый GGplot

0 голосов
/ 16 октября 2019

пример кода

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

Моя цель - добавить текст «Группа A» и «Группа B» в указанные строки вограненный GGPlot. Я видел, как сделать это внутри каждого графика, но можно ли аннотировать снаружи, как в приведенном выше графическом примере?

1 Ответ

0 голосов
/ 16 октября 2019

Использование пакета 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

Также проверьте параметр labels = "AUTO" в ggarrange.

...