Reputation: 163
I would like to make a simple table and add different specific background color to different values of all cells (if 0 then color x1, if between 0 and 20 then color x2, if between 21-40 then color x3 etc.). I couldn't find out how this works except of going through each and every column in my dataframe. How can I refer to all cells in all columns instead of going through column1 (see below) then add column2, column3 etc...? I dont want a heat table because I need to exactly specifiy my color values
library(gt)
testdf = data.frame(
Column1 = c(0,80,3,10,100),
Column2 = c(0,50,80,2,55)
)
gt_tbl <- testdf %>%
gt() %>%
tab_style(
style = list(
cell_fill(color = "red"),
cell_text(weight = "normal")
),
locations = cells_body(
columns = vars(Column1),
rows = Column1 == 0)
) %>%
tab_style(
style = list(
cell_fill(color = "blue"),
cell_text(weight = "normal")
),
locations = cells_body(
columns = vars(Column1),
rows = Column1 > 0 & Column1 < 20)
)
gt_tbl
Upvotes: 0
Views: 286
Reputation: 6813
This could be achieved using add_css_conditional_column
from the tableHTML
package. it allows to apply certain css to fields in the table, when a condition applies:
library(tableHTML)
testdf = data.frame(
Column1 = c(0,80,3,10,100),
Column2 = c(0,50,80,2,55)
)
testdf %>%
tableHTML(rownames=FALSE,
widths = c(100, 100)) %>%
# add_theme("rshiny-blue") %>% # optional, if predefined theme is desired
add_css_conditional_column(conditional = "==",
value = 0,
css = list("background-color",
"red"),
columns = 1:2) %>%
add_css_conditional_column(conditional = "between",
between = c(1, 20),
css = list("background-color",
"blue"),
columns = 1:2) %>%
add_css_conditional_column(conditional = "between",
between = c(21, 40),
css = list("background-color",
"green"),
columns = 1:2)
The result is:
Upvotes: 2