示例代码
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")
我的目标是在多面GGPlot中的指定行中添加文本“ Group A”和“ Group B”。我已经看到了如何在每个图的内部进行此操作,但是是否可以像上面的图形示例一样在外部进行注释?
答案 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")
还要在ggarrange中选中选项labels = "AUTO"
。