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


i'm trying add data-table graph made in ggplot (similar excel functionality flexibility change axis on)

i've had few goes @ , keep hitting problem scaling 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) = 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

2 ggplots

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

using straight table grob , grid.draw

and 3) was

grid.newpage() print(a + annotation_custom(grob=xtb,xmin=0,xmax=37,ymin=450,ymax=460)) 

which produced

using annotate_custom

of them option 2 best if scale tablegrob same size plot, i've no idea how that. pointers on how take further? - thanks

you can try new version of tablegrob; resulting gtable width/height can set 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) 

enter image description here


Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -