styleColorBar:使颜色条的大小与列的绝对值成正比

har*_*mut 6 datatable r dt

使用styleColorBar,如何使颜色条的大小与列的绝对值成正比?与此相反,在下面的示例中,查看cyl列,红色条越大,值越大。

代码:

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
Run Code Online (Sandbox Code Playgroud)

结果: 在此处输入图片说明 我知道这里那里已经回答非常相似的问题。

但是这两个例子似乎比我的更复杂。前者处理基于另一列格式化一列。后者的颜色条的方向取决于标志。我认为对于我的案例可能存在一个更简单的技巧......

谢谢

luk*_*keA 7

这里有一个hackish的方式:styleColorBar产生一些JavaScript,在那里你可以替代valueMath.abs(value)。为了获得正确的限制,我还采取了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
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明