grid.extra中grid.arrange的背景颜色

时间:2016-08-22 03:30:33

标签: ggplot2 gridextra

所以我试图使用gridExtra绘制一些ggplots及其图例。图例出现在白色背景上的最后一个单元格中 - 我想更改那里的背景颜色,以便白色背景消失。我怎么能这样做?

这是我的代码:

library(reshape)
library(ggplot2)
library(plyr)
library(wq)
library(gridExtra)
library(lattice)
library(grid)

testVisualization <- function()
{
  set.seed(123)

  xx <- sample(seq(from = 20, to = 50, by = 5), size = 50, replace = TRUE)
  yy <- sample(seq(from = 1, to = 50), size = 50, replace = TRUE)
  zz <- sample(seq(from = 1, to = 10, by = 1), size = 50, replace = TRUE)

  dd <- data.frame(xx,yy,zz)

  colRainbow <- rainbow(n, s = 1, v = 1, start = 0, end = max(1, n - 1)/n, alpha = 1)
  gg <- ggplot() + geom_point(data=dd, aes(x=xx, y=yy, colour=zz))+
    theme_custom()

  lay2 <- rbind(c(1,1,1,1,1), 
                c(2,2,3,3,4))
  legg1 <- g_legend(gg)

  grid.arrange( 
    gg+guides(fill=FALSE, colour=FALSE, size=FALSE),
    gg+guides(fill=FALSE, colour=FALSE, size=FALSE),
    gg+guides(fill=FALSE, colour=FALSE, size=FALSE),
    legg1,
    layout_matrix=lay2)
}

theme_custom <- function()
{
  theme(
    plot.background = element_rect(fill = "#002B36", colour = "#002B36"),
    panel.background = element_rect(fill = "#002B36"),
    panel.background = element_rect(fill = "#002B36"),
    legend.background = element_rect(fill="#002B36", colour = "#002B36"),
    legend.margin = unit(c(-4, -4), "cm"),
    legend.key = element_rect(fill="#002B36", colour ="#002B36"),
    legend.text =element_text(colour = "#DCD427"),
    legend.title=element_text(colour = "#DCD427")

  )
}

g_legend<-function(a.gplot){
  tmp <- ggplot_gtable(ggplot_build(a.gplot))
  leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
  legend <- tmp$grobs[[leg]]
  #+ legend.margin = unit(-0.5, "cm")
  legend
}

And here's the plot I get. I would like the white spaces around the legend cell to disappear

1 个答案:

答案 0 :(得分:2)

试试这个,

g_legend<-function(gg){
  tmp <- ggplot_gtable(ggplot_build(gg))
  id <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
  leg <- tmp$grobs[[id]]
  bkg <- leg[["grobs"]][[1]][["grobs"]][leg[["grobs"]][[1]][["layout"]][,"name"]=="background"][[1]][["gp"]][["fill"]]
  leg <- gtable_add_grob(leg, grobs = rectGrob(gp=gpar(fill=bkg, col="red", lty=2)),
                         t=1, l=1, b=nrow(leg), r=ncol(leg), z=-1)

  # no idea why, but the legend seems to have weird negative sizes
  # that make the background overlap with neighbouring elements
  # workaround: set those unidentified sizes to 1null 
  leg$widths[c(1,2,4,5)] <- unit(rep(1,4),"null")
  leg$heights[c(1,2,4,5)] <- unit(rep(1,4),"null")
  leg
}

enter image description here