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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With