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

标签 r datatable 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

结果:
enter image description here
我知道已经回答了非常相似的问题 herethere .

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

谢谢

最佳答案

这是一种骇人听闻的方式: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

enter image description here

关于r - styleColorBar : have the size of the color bar be proportional to absolute values of a column,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44504024/

相关文章:

r - 如何循环遍历 lmerTest 输出列表以提取偏差分量

c# - WPF MVVM Bind DataTable to DataGrid 不显示数据

javascript - 是否可以为 datatables.net 子行编写 If/Else 语句来删除 null 使该行说是、否或留空?

Rmarkdown 使用该行的下载按钮下载数据

r - 为什么 knitr 代码块中的 $PATH 与终端中的 $PATH 不同?

r - 将最近的邮政编码分配给 R 中的一组坐标的算法

r - group_by 变量的 n 个唯一顺序值

C# 读取 csv,计算一些东西,导出另一个 csv

r - DataTables 也应用列格式来过滤

r - Shiny 模块内的DataTable行选择