I am trying to colour specific cells in a gtsummary table of the mtcars data set. The code below provides a gtsummary table with 4 columns, the first referring to the variables, and the remaining three columns referring to the three levels of the "cyl" factor.
The objective is to be able to pinpoint specific cells and assign to them a specific background colour. For instance, column 3, row 3 is the intersection of cyl = 6 and the value for disp for cyl = 6. I want that cell to be red, and the cell corresponding to cyl = 8 and the row 6 (variable wt) to be orange.
I have come across other pages where it is shown how you can colour an entire column in one colour, but have not found how you can target specific cells across columns with a specific colour, based on their location, value, or even text.
Any help would be much appreciated.
library(gtsummary)
library(tidyverse)
library(reprex)
mtcars %>%
tbl_summary(by = cyl)
You'll need the gt
as well package for the following method
base::library(package = gtsummary)
base::library(package = gt)
base::library(package = tidyverse)
mtcars %>%
gtsummary::tbl_summary(by = cyl) %>%
gtsummary::as_gt() %>% # Need to conver the tbl_summary obj to gt obj for following functions
gt::tab_style_body(
style = gt::cell_fill(color = "#a83232"), # Adjust this color to taste
values = "168 (160, 196)"
) %>%
gt::tab_style_body(
style = gt::cell_fill(color = "#eb4f0c"), # Adjust this color to taste
values = "193 (176, 241)"
)
Note the place where you can adjust the hex codes for the colors, and I am identifying the cells by the values that they have in them . Code results in this:
See here for more formatting options for gt objects. Make sure to mark as solution if this works well for you!