Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GridExtra: Align text to right

Tags:

r

gridextra

I'm using gridExtra package of R.
I'd like to align the numbers of the second column to the left, without changing the alignment of the names of first column. Is it possible? Thank you!

library(gridExtra)
library(grid)

names=c("name1","name2","name3","long name","very long name")
values1=c(100000000,70000,20,600000000000000000,500)
values1=format(values1,big.mark=".",decimal.mark=",",scientific=FALSE)

d=data.frame(names=names,values1=values1)
g1 <- tableGrob(d)
grid.newpage()
grid.draw(g1)

enter image description here

Thank you.

like image 847
John M Avatar asked Jan 23 '16 11:01

John M


2 Answers

Using an idea from the Accessing existing grobs in the table section of the gridExtra wiki, you can edit the grobs of the gtable directly.

g1 <- tableGrob(d)

# identify the grobs to change 
# third column of gtable and core foreground text
id <- which(grepl("core-fg", g1$layout$name ) & g1$layout$l == 3 )

# loop through grobs and change relevant parts
for (i in id) {
      g1$grobs[[i]]$x <- unit(1, "npc")
      g1$grobs[[i]]$hjust <- 1
      }

grid.newpage()
grid.draw(g1)

enter image description here

like image 84
user20650 Avatar answered Oct 26 '22 08:10

user20650


You can try this:

library(gridExtra)
names=c("name1","name2","name3","long name","very long name")
values1=c(100000000,70000,20,600000000000000000,500)
values1=format(values1,big.mark=".",decimal.mark=",",scientific=FALSE)
d <- data.frame(names=names,values1=values1)

g1 <- tableGrob(d[,1, drop = FALSE])
tt2 <- ttheme_default(core = list(fg_params=list(hjust=1, x=1)),
                      rowhead = list(fg_params=list(hjust=1, x=1)))
g2 <- tableGrob(d[,2, drop = FALSE], rows = NULL, theme = tt2)

grid.arrange(arrangeGrob(grobs = list(g1, g2 ), nrow = 1) , widths = c(1,1))

enter image description here

like image 27
Mamoun Benghezal Avatar answered Oct 26 '22 07:10

Mamoun Benghezal