2017-06-12 18 views
1

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

代码:

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

但这两个例子看起来都比我的复杂。前者处理基于另一列的格式化列。后者的颜色条的方向取决于标志。我想,也许是一个简单的伎俩存在我的情况...

谢谢

回答

1

这里有一个hackish的方法: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 

enter image description here