gtable对象的透明度

7
我正在尝试生成具有透明背景的ggplot对象的png文件。当我直接使用panel.background=element_rect(fill = "transparent",colour = NA)在ggplot对象上时,我得到了想要的结果。
现在我正在尝试对图进行一些修改(如向facets添加标签,就像这样How do you add a general label to facets in ggplot2?)。但是,当我绘制修改后的gtable对象时,背景是浅灰色的,带有细白线。 enter image description here 而如果直接绘制ggplot对象,则支持透明度。 enter image description here 以下是我使用的代码:
data <- data.table(a = seq(1,5), b=sample.int(5,50,replace=TRUE), c=rnorm(100))

plotSlices <- function(input, rowfacet, colfacet, metric, label, facetlabels=FALSE){
  calc <- substitute(metric)
  bygroup<-c(rowfacet,colfacet)
  aggregates <- input[,eval(calc),by=bygroup]

  chart <- ggplot(aggregates) + 
    geom_bar(stat="identity") + 
    aes(x="", y=V1, fill=V1>0) + 
    facet_grid(as.formula(sprintf("%s ~ %s", rowfacet, colfacet))) +
    coord_flip() +
    xlab("") +
    ylab(label) +
    theme(legend.position = "none", 
          axis.title=element_text(size=16, color="white"),
          axis.ticks.y=element_blank(),
          panel.grid.major.y=element_blank(),
          panel.grid.major.y=element_line(colour = "grey25"),
          panel.grid.minor.x=element_blank(),
          plot.background=element_rect(fill = "transparent",colour = NA),
          panel.background=element_rect(fill = "transparent",colour = NA)
    )

  if (facetlabels) {
    return(LabelFacets(chart, rowfacet, colfacet))  
  }
  else {
    return(chart)
  }
}
LabelFacets <- function(plot, rowfacet, colfacet) {
  grob <- ggplotGrob(plot)
  grob <- gtable_add_cols(grob, grob$widths[[7]])
  grob <- gtable_add_grob(grob, list(rectGrob(gp = gpar(col = NA, fill = gray(0.5))),
                                     textGrob(rowfacet, rot = -90, gp = gpar(col = gray(1)))),
                          4, 14, 12, name = paste(runif(2)))
  grob <- gtable_add_rows(grob, grob$widths[[2]], 2)
  grob <- gtable_add_grob(grob, list(rectGrob(gp = gpar(col = NA, fill = gray(0.5))),
                                     textGrob(colfacet, gp = gpar(col = gray(1)))),
                          3, 4, 3, 12, name = paste(runif(2)))
  return(grob)
}
png(filename = "test.png", bg = "transparent")
plot(plotSlices(data, "a", "b", mean(c), "Label", FALSE))
dev.off()

png(filename = "test2.png", bg = "transparent")
plot(plotSlices(data, "a", "b", mean(c), "Label", TRUE))
dev.off()

如果您修改了 grob <- gtable_add_cols(grob, grob$widths[[7]]),这会有什么影响吗? - user2510479
7
不要在 gtable 上使用 plot(),改用 grid.draw() - baptiste
1个回答

9

Baptiste帮我解决了这个问题。问题是使用plot()显示gtable对象,而应该使用grid.draw()。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接