Combining grid_arrange_shared_legend() and facet_wrap_labeller() in R

可紊 提交于 2019-12-02 01:06:14

You need to pass the gtable instead of the ggplot,

library(gtable)
library("ggplot2")
library(grid)
set.seed(1)
d <- data.frame(
  f1 = rep(LETTERS[1:3], each = 100),
  f2 = rep(letters[1:3], 100),
  v1 = runif(3 * 100),
  v2 = rnorm(3 * 100)
)
p1 <- ggplot(d, aes(v1, v2, color = f2)) + geom_point() + facet_wrap(~f1)
p2 <- ggplot(d, aes(v1, v2, color = f2)) + geom_smooth() + facet_wrap(~f1)


facet_wrap_labeller <- function(g, labels=NULL) {

  gg <- g$grobs      
  strips <- grep("strip_t", names(gg))

  for(ii in seq_along(labels))  {
    oldgrob <- getGrob(gg[[strips[ii]]], "strip.text", 
                       grep=TRUE, global=TRUE)
    newgrob <- editGrob(oldgrob,label=labels[ii])
    gg[[strips[ii]]]$children[[oldgrob$name]] <- newgrob
  }
  g$grobs <- gg
  g
}


combined_fun <- function(p1, p2, labs1) {

  g1 <- ggplotGrob(p1 + theme(legend.position = "right"))
  g2 <- ggplotGrob(p2 + theme(legend.position = "none")) 

  g1 <- facet_wrap_labeller(g1, labs1)

  legend <- gtable_filter(g1, "guide-box", trim = TRUE)
  g1p <- g1[,-(ncol(g1)-1)]
  lw <- sum(legend$width)

  g12 <- rbind(g1p, g2, size="first")
  g12$widths <- unit.pmax(g1p$widths, g2$widths)
  g12 <- gtable_add_cols(g12, widths = lw)
  g12 <- gtable_add_grob(g12, legend, 
                         t = 1, l = ncol(g12), b = nrow(g12))
  g12
}


test <- combined_fun(p1, p2, labs1 = c(
                      expression(paste("A ", italic(italic))),
                      expression(paste("B ", italic(italic))), 
                      expression(paste("C ", italic(italic)))
                    )
)

grid.draw(test)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!