在图例旁边没有空格的grid.draw中保存图例

时间:2014-02-24 14:34:55

标签: r ggplot2

我想从情节中说明传说:

a<-rnorm(100)
b<-runif(100)
ba<-cbind(a,b)
colnames(ba)<-c("a","b")
ba<-melt(ba,id.vars=1:1)
colnames(ba)<-c("c","variable","value")
plot1<-ggplot(q,aes(x=c,y=value,colour=variable,size=variable))+geom_point()+theme(legend.position="right")

现在我从grob中提取传奇:

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]]
return(legend)}


legend<-g_legend(plot1)

我可以使用grid.draw保存此图例:     PDF( “plot.pdf”)     grid.draw(传奇)     dev.off()

生成的图像将包含具有大量空白区域的图例。有没有办法只绘制图例而不是旁边有太多空间?

1 个答案:

答案 0 :(得分:2)

gg <- gtable::gtable_filter(x=ggplotGrob(plot1), 
               pattern="guide", trim=TRUE)[["grobs"]][[1]][["grobs"]][[1]]

pdf("legend.pdf", 
    width=convertWidth(sum(gg$width), "in", valueOnly=TRUE),
    height=convertHeight(sum(gg$heights), "in", valueOnly=TRUE))
grid.draw(gg)
dev.off()
相关问题