styleColorBar:让颜色条的大小与列的绝对值成比例

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

使用 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

结果: 我知道已经回答了非常相似的问题 and

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

谢谢

这是一种骇人听闻的方法:styleColorBar 生成一些 JavaScript,您可以在其中用 Math.abs(value) 替换 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

试试这个:

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

它适用于我闪亮的应用程序。它只是对数据创建了一个 0 限制,从而解决了问题。