2016-08-22 48 views
1

所以我想用gridExtra来绘制几个ggplots和它们的图例。图例出现在白色背景上的最后一个单元中 - 我想在那里更改背景颜色,以便白色背景消失。我怎样才能做到这一点?gridExtra中grid.arrange的背景颜色

这里是我的代码:

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

回答

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

+0

嗨巴蒂斯特,感谢您的回答。但是,这样做对你是否正常?当我在上面添加我的代码时,我得到以下错误:。在grid.Call.graphics中的错误(L_setviewport,vp,TRUE): INTEGER()只能应用于'整数'而不是'NULL' – petiteparticule

+0

完美!它适用于R 3.3.1(我在另一台计算机R 3.2上)。非常感谢! – petiteparticule