John M
John M

Reputation: 217

GridExtra: Align text to right

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.

Upvotes: 6

Views: 3914

Answers (3)

baptiste
baptiste

Reputation: 77096

Here's another option,

g1 <-  tableGrob(d[,-2, drop=FALSE])
g2 <- tableGrob(d[,2, drop=FALSE], rows = NULL,
                theme = ttheme_default(core = list(fg_params=list(hjust=1, x=0.95))))
g <- gtable_combine(g1,g2)
grid.newpage()
grid.draw(g)

enter image description here

Upvotes: 2

Mamoun Benghezal
Mamoun Benghezal

Reputation: 5314

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

Upvotes: 2

user20650
user20650

Reputation: 25854

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

Upvotes: 3

Related Questions