Legend for Color-Coded Table in R
I've Created a Color-Coded Table in R's Gt Package with Conditional Formatting. I Would Like to Include Something That Will Function as a Legend to Signify...
I've created a color-coded table in R's gt package with conditional formatting. I would like to include something that will function as a legend to signify what the colors mean. For instance (for simplicity):
a <- c(1 , 3 , 5 , 9)
b <- c(1 , 2 , 6 , 10)
ab <- data.frame(a , b)
library(gt)
gt(ab) %>%
tab_style(style = list(cell_fill(color = '#E69F00') ,
cell_text(weight = 'bold')) ,
locations = cells_body(columns = vars(a) ,
rows = (a > b)))
This produces an example of the color-coded table. I'd like to have a notation in source notes or a location below the figures that that would reproduce the color and indicate in text that the colored cell meant that a was higher than b. Any help or referral appreciated!
1 Answer
I poked around and found an answer. I'm sure more experienced coders could find something better, but adding html instructions to a tab_source_note worked for me. It's just proof of concept; I can change font size to make it nicer. Passing it on in case someone else has this challenge.
a <- c(1 , 3 , 5 , 9)
b <- c(1 , 2 , 6 , 10)
ab <- data.frame(a , b)
library(gt)
#> Warning: package 'gt' was built under R version 3.6.3
gt(ab) %>%
tab_style(style = list(cell_fill(color = '#E69F00') ,
cell_text(weight = 'bold')) ,
locations = cells_body(columns = vars(a) ,
rows = (a > b))) %>%
tab_source_note(html('<pre><span style="background-color: #E69F00;"
> </span> = Higher</pre>'))