使用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)
但是这两个例子似乎比我的更复杂。前者处理基于另一列格式化一列。后者的颜色条的方向取决于标志。我认为对于我的案例可能存在一个更简单的技巧......
谢谢
这里有一个hackish的方式:styleColorBar产生一些JavaScript,在那里你可以替代value的Math.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)