首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >gtable对象中的透明度

gtable对象中的透明度
EN

Stack Overflow用户
提问于 2013-09-27 01:56:16
回答 1查看 1.2K关注 0票数 6

我正在尝试产生透明背景的ggplot对象的png文件。当我在panel.background=element_rect(fill = "transparent",colour = NA)中直接使用ggplot对象时,我得到了我想要的结果。

我现在正在尝试对图进行一些修改(向面添加标签,如下面的How do you add a general label to facets in ggplot2?)

当我绘制修改后的gtable对象时,背景是浅灰色的细白线,而不是透明的背景。

而如果我直接绘制ggplot对象,它确实支持透明度

下面是我使用的代码:

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

回答 1

Stack Overflow用户

发布于 2013-09-27 06:29:17

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

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

https://stackoverflow.com/questions/19035287

复制
相关文章

相似问题

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