Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rotate the column headers with R package gt?

Tags:

r

r-markdown

gt

Is there a way to rotate by 90 degrees the column headers with the gt package and make them vertical?

Thanks in advance!

like image 883
andreranza Avatar asked Oct 30 '25 17:10

andreranza


2 Answers

There's not yet a built-in way of doing this but you can use custom CSS to style the table, although you may need to do some additional fine tuning to get it to look ok.

library(gt)

head(mtcars) |> 
  gt(id = "mygt")  |> 
  cols_align("center", everything()) |> 
  opt_css(
  css = "
    #mygt .gt_col_heading {
    writing-mode: vertical-rl;
    transform: scale(-1);
    vertical-align: middle;
    font-weight: bold;
    }
    "
)  

enter image description here

like image 83
Ritchie Sacramento Avatar answered Nov 01 '25 07:11

Ritchie Sacramento


It looks like this might not be a feature yet in gt, as it is still in the queue as an enhancement.

Another option would be to use kableExtra (code from here):

library(kableExtra)
library(knitr)

kable(head(mtcars), "html") %>%
  kable_styling("striped", full_width = F) %>%
  row_spec(0, angle = -90)

Output

enter image description here

Or using gridExtra (code from here):

library(gridExtra)
library(grid)

tt = ttheme_default(colhead=list(fg_params=list(rot=90)))
grid.newpage()
grid.table(head(mtcars), theme=tt)

Output

enter image description here

like image 36
AndrewGB Avatar answered Nov 01 '25 07:11

AndrewGB