首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >grid.arrange在gridExtra中的背景色

grid.arrange在gridExtra中的背景色
EN

Stack Overflow用户
提问于 2016-08-22 03:30:33
回答 1查看 1.3K关注 0票数 1

所以我试着用gridExtra绘制一些few的情节和他们的传说。图例出现在白色背景上的最后一个单元格中--我想在那里更改背景色,这样白色背景就消失了。我怎么能这么做?

这是我的密码:

代码语言:javascript
复制
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
}

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-08-23 09:14:15

尝尝这个,

代码语言:javascript
复制
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
}

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39071011

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档