3

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

Thanks in advance!

andreranza
  • 93
  • 6

2 Answers2

4

As Andrew has noted, 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 of the elements to get it to look ok.

library(gt)

head(mtcars) %>%
  gt(id = "mygt") %>%
  tab_options(column_labels.padding = px(15),
              column_labels.padding.horizontal = px(7)) %>%
  cols_align("center", everything()) %>%
  opt_css(
  css = "
    #mygt .gt_col_heading {
      text-align: center;
      transform: rotate(-90deg);
      font-weight: bold;
    }
    "
)

enter image description here

Ritchie Sacramento
  • 29,890
  • 4
  • 48
  • 56
  • Yes ... did not work for me ... would be useful – Markm0705 Jan 28 '23 at 23:32
  • 1
    @Markm0705 - You may want to post a new question outlining your problem if the code above is not working for you. As far as I know the CSS should be recognized by all major browsers but as mentioned in my answer you may need to adjust padding depending on the size and length of text included in the heading. – Ritchie Sacramento Jan 31 '23 at 09:37
1

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

AndrewGB
  • 16,126
  • 5
  • 18
  • 49