How do I customize particular columns for a tableGrob in R?

不羁的心 提交于 2019-12-10 14:55:17

问题


I'm looking to customise particular columns in my tableGrob, for this reproducible example I have chosen to look at customising justification.

Say you have the following dataframe:

df <- data.frame(Order = c(1:3), Name = c("Adam", "Ben", "Charlie"), Score = c(4, 8, 9))

And you want to use the package gridExtra to present the table:

dfGrob <- tableGrob(df, rows = NULL)
grid.arrange(dfGrob)

You can adjust the alignment of the columns by adjusting the theme used to build the grob, for example:

tt1 <- ttheme_default(core=list(fg_params=list(hjust= 0, x=0.05)),
                  colhead=list(fg_params=list(hjust=0, x=0.1)))


dfGrob <- tableGrob(df, rows = NULL, theme = tt1)
grid.arrange(dfGrob)

However, this adjusts the justification for all columns. Say I just want to left justify the Order Column, and leave the others in their central justification position, how would I do that?

I have experimented with:

tt1 <- ttheme_default(core=list(fg_params=list(hjust= c(0, 0.5, 0.5), x=c(0.15, 0.5, 0.5))),
                  colhead=list(fg_params=list(hjust=1, x=0.95)))

dfGrob <- tableGrob(df, rows = NULL, theme = tt1)
grid.arrange(dfGrob)

But this just seems to customise by row. How do I adjust this code to customise by column instead?


回答1:


it's a bit fiddly but you can specify the parameters for all elements,

library(grid)
library(gridExtra)

df <- data.frame(Order = c(1:3),
                 Name = c("Adam", "Ben", "Charlie"), 
                 Score = c(4, 8, 9))

hj <- matrix(c(0, 0.5, 1), ncol=3, nrow=nrow(df), byrow=TRUE)
x <- matrix(c(0, 0.5, 1), ncol=3, nrow=nrow(df), byrow=TRUE)

tt1 <- ttheme_default(core=list(fg_params=list(hjust = as.vector(hj), 
                                               x = as.vector(x))),
                      colhead=list(fg_params=list(hjust=1, x=0.95)))


dfGrob <- tableGrob(df, rows = NULL, theme = tt1)
grid.newpage()
grid.draw(dfGrob)

The recycling logic defaults to column wise, because most often a table has rows of alternating colours. It should be possible to special-case the horizontal justification parameters to make this a bit more user-friendly. Feel free to submit a PR.



来源:https://stackoverflow.com/questions/36454028/how-do-i-customize-particular-columns-for-a-tablegrob-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!