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

2

8

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

Ebonieebonite answered 12/6, 2017 at 16:9 Comment(0)
G
7

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

Gustavogustavus answered 12/6, 2017 at 16:26 Comment(0)
P
2

Try this:

background = styleColorBar(c(0,data$mpg), 'lightblue'),

It works on my shiny app. It just creates a 0 limit to the data, which solves the problem.

Phillada answered 13/3, 2019 at 15:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.