与 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
结果:
我知道已经回答了非常相似的问题 here和 there .
但是这两个例子似乎比我的更复杂。前者处理基于另一列格式化一列。后者的颜色条的方向取决于标志。我认为对于我的案例可能存在一个更简单的技巧......
谢谢
最佳答案
这是一种骇人听闻的方式: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
关于r - styleColorBar : have the size of the color bar be proportional to absolute values of a column,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44504024/