Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

styleColorBar: have the size of the color bar be proportional to absolute values of a column

Tags:

r

datatable

dt

With styleColorBar, how can I get size of the color bar to be proportional to the absolute value of a column? In contrast to this, in the example below, looking at the cyl column, the red bar is larger for greater values.

Code:

data <- head(mtcars[,1:4])
data[,2] <- -data[,2]
data
out <- datatable(data, rownames = FALSE) %>%
  formatStyle('mpg',
              background = styleColorBar(data$mpg, 'lightblue'),
              backgroundSize = '95% 50%',
              backgroundRepeat = 'no-repeat',
              backgroundPosition = 'right') %>%
  formatStyle('cyl',
              background = styleColorBar(data$cyl, 'red'),
              backgroundSize = '95% 50%',
              backgroundRepeat = 'no-repeat',
              backgroundPosition = 'right')
out

Result: enter image description here I am aware that very similar questions have been answered here and there.

But both examples seem more intricate than mine. The former deals with formatting a column based on another column. The latter has the direction of the color bar depend on the sign. I thought that perhaps a simpler trick exists for my case...

Thank you

like image 458
hartmut Avatar asked Jun 12 '17 16:06

hartmut


Video Answer


1 Answers

Here's one hackish way: styleColorBar produces some JavaScript, where you can substitute value by Math.abs(value). To get the limits right, I also took abs(data$cyl):

library(DT)
data <- head(mtcars[,1:4])
data[,2] <- -data[,2]
data
out <- datatable(data, rownames = FALSE) %>%
  formatStyle('mpg',
              background = styleColorBar(data$mpg, 'lightblue'),
              backgroundSize = '95% 50%',
              backgroundRepeat = 'no-repeat',
              backgroundPosition = 'right') %>%
  formatStyle('cyl',
              background = gsub(
                "value", "Math.abs(value)", 
                styleColorBar(abs(data$cyl), 'red'),
                fixed=T),
              backgroundSize = '95% 50%',
              backgroundRepeat = 'no-repeat',
              backgroundPosition = 'right')
out

enter image description here

like image 122
lukeA Avatar answered Sep 28 '22 07:09

lukeA