R adding a datatable to a ggplot graph using viewPorts : Scaling the Grob

ggplot2, gridextra, r, r-grid, viewport

Solution

You can try the new version of `tableGrob`; the resulting gtable width/height can be set to a specific size (here equi-distributed npc units)

library(ggplot2)
library(gridExtra)
library(grid)
tg <- tableGrob(head(iris), rows=NULL)
tg$widths <- unit(rep(1/ncol(tg),ncol(tg)),"npc")
tg$heights <- unit(rep(1/nrow(tg),nrow(tg)),"npc")

qplot(colnames(iris), geom="bar")+ theme_bw() +
  scale_x_discrete(expand=c(0,0)) +
  scale_y_continuous(lim=c(0,2), expand=c(0,0)) +
  annotation_custom(ymin=1, ymax=2, xmin=-Inf, xmax=Inf, tg)

Problem

I'm trying to add a data-table to a graph made in ggplot (similar to the excel functionality but with the flexibility to change the axis its on) I've had a few goes at it and keep hitting a problem with scaling so attempt 1) was ``` library(grid) library(gridExtra) library(ggplot2) xta=data.frame(f=rnorm(37,mean=400,sd=50)) xta$n=0 for(i in 1:37){xta$n[i]<-paste(sample(letters,4),collapse='')} xta$c=0 for(i in 1:37){xta$c[i]<-sample((1:6),1)} rect=data.frame(xmi=seq(0.5,36.5,1),xma=seq(1.5,37.5,1),ymi=0,yma=10) xta=cbind(xta,rect) a = ggplot(data=xta,aes(x=n,y=f,fill=c)) + geom_bar(stat='identity') b = ggplot(data=xta,aes(x=n,y=5,label=round(f,1))) + geom_text(size=4) + geom_rect(aes(xmin=xmi,xmax=xma,ymin=ymi,ymax=yma),alpha=0,color='black') z = theme(axis.text=element_blank(),panel.background=element_rect(fill='white'),axis.ticks=element_blank(),axis.title=element_blank()) b=b+z la=grid.layout(nrow=2,ncol=1,heights=c(0.15,2),default.units=c('null','null')) grid.show.layout(la) grid.newpage() pushViewport(viewport(layout=la)) print(a,vp=viewport(layout.pos.row=2,layout.pos.col=1)) print(b,vp=viewport(layout.pos.row=1,layout.pos.col=1)) ``` which produced the second attempt 2) was ``` xta1=data.frame(t(round(xta$f,1))) xtb=tableGrob(xta1,show.rownames=F,show.colnames=F,show.vlines=T,gpar.corefill=gpar(fill='white',col='black'),gp=gpar(fontsize=12),vp=viewport(layout.pos.row=1,layout.pos.col=1)) grid.newpage() la=grid.layout(nrow=2,ncol=1,heights=c(0.15,2),default.units=c('null','null')) grid.show.layout(la) grid.newpage() pushViewport(viewport(layout=la)) print(a,vp=viewport(layout.pos.row=2,layout.pos.col=1)) grid.draw(xtb) ``` which produced and finally 3) was ``` grid.newpage() print(a + annotation_custom(grob=xtb,xmin=0,xmax=37,ymin=450,ymax=460)) ``` which produced Of them option 2 would be the best if I could scale the tableGrob to the same size as the plot, but I've no idea how to do that. Any pointers on how to take this further? - Thanks

Original source