Reputation: 6220
I have the following data.frame which I would like to plot with ggplot2:
df = data.frame(mean=c(1.96535,2.133604,1.99303,1.865004,2.181713,1.909511,2.047971,1.676599,2.143763,1.939875,1.816028,1.95465,2.153445,1.802517,2.141799,1.722428),
sd=c(0.0595173,0.03884202,0.0570006,0.04934336,0.04008221,0.05108064,0.0463556,0.06272475,0.04321496,0.05283728,0.05894342,0.05160038,0.04679423,0.05305525,0.04626291,0.0573123),
par=as.factor(c("p","p","m","m","p","p","m","m","m","m","p","p","m","m","p","p")),
group=as.factor(c("iF","iF","iF","iF","iM","iM","iM","iM","RF","RF","RF","RF","RM","RM","RM","RM")),
rep=c(1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2))
This is my code for doing that:
p <- ggplot(df,aes(factor(rep),y=mean,ymin=mean-2*sd,ymax=mean+2*sd,color=factor(par)))
p <- p + geom_pointrange()+facet_wrap(~group, ncol = 4)+scale_color_manual(values = c("blue","red"),labels = c("p","m"),name = "par id")
p <- p + ggtitle("test")
p <- p + labs(y="log(y)",x="rep")
which produces this figure:
I would like to add this data.frame under the legend:
leg.df = data.frame(statistic = c("pp(par)","pp(g)","pp(s)","fc(p/m)"), value = c(0.96,0.94,0.78,1.5))
I followed this stackoverflow thread for inserting a table under the legend in a ggplot2 using this code:
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(p)
grid.newpage()
vp1 <- viewport(width = 0.75, height = 1, x = 0.375, y = .5)
vpleg <- viewport(width = 0.25, height = 0.5, x = 0.85, y = 0.75)
subvp <- viewport(width = 0.3, height = 0.3, x = 0.85, y = 0.25)
print(p + theme(legend.position = "none"), vp = vp1)
upViewport(0)
pushViewport(vpleg)
grid.draw(legend)
upViewport(0)
pushViewport(subvp)
my_table <- tableGrob(leg.df, gpar.coretext = gpar(fontsize=8), gpar.coltext=gpar(fontsize=8), gpar.rowtext=gpar(fontsize=8), show.rownames = FALSE)
grid.draw(my_table)
which produces exactly what I want:
The only problem is that I cannot get it to print everything to a file. I tried specifying pdf(<file>)
in front of the entire block of code and dev.off()
after it, but that doesn't seem to work. So I can only get it to print to the R screen.
So I guess I should be handling the legend part differently but I have no idea how.
Any suggestions?
Upvotes: 2
Views: 2661
Reputation: 121618
Use the second solution in the link with arrangeGrob
:
leg.df.grob <- tableGrob(leg.df, gpar.coretext =gpar(fontsize=8),
par.coltext=gpar(fontsize=8),
gpar.rowtext=gpar(fontsize=8))
### final result
library(gridExtra)
pp <- arrangeGrob(p + theme(legend.position = "none"),
arrangeGrob(leg.df.grob, legend), ncol = 2)
Then you can save using ggsave
:
ggsave('plot.png',pp)
Upvotes: 2