问题
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)
Thank you.
回答1:
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)
回答2:
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))
回答3:
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)
来源:https://stackoverflow.com/questions/34962951/gridextra-align-text-to-right