I am looking for a way to create a conditional bar plot as part of a gt
table (the wonderful grammar of tables package). It seems to be possible in DT
's datatable
as shown here styleColorBar Center and shift Left/Right dependent on Sign. Here is an image of what I want and below is code to generate this image in DT
. I am looking for a gt
solution though.
library(tidyverse)
library(DT)
# custom function that uses CSS gradients to make the kind of bars I need
color_from_middle <- function (data, color1,color2)
{
max_val=max(abs(data))
JS(sprintf("isNaN(parseFloat(value)) || value < 0 ? 'linear-gradient(90deg, transparent, transparent ' + (50 + value/%s * 50) + '%%, %s ' + (50 + value/%s * 50) + '%%,%s 50%%,transparent 50%%)': 'linear-gradient(90deg, transparent, transparent 50%%, %s 50%%, %s ' + (50 + value/%s * 50) + '%%, transparent ' + (50 + value/%s * 50) + '%%)'",
max_val,color1,max_val,color1,color2,color2,max_val,max_val))
}
mtcars %>%
rownames_to_column() %>%
select(rowname, mpg) %>%
head(10) %>%
mutate(mpg = (mpg - 20) %>% round) %>%
datatable() %>%
formatStyle(
"mpg",
background = color_from_middle(mtcars$mpg,'red','green')
)
tab_bar
will add the bars to the specified column. It scales the values to be between0
and100
. Values of0
get mapped to50
.tab_style
is used to on each of the values to set the background gradient.Here it is with
mtcars
.