我正在开发一个R Shiny应用程序,并希望根据我提供的颜色矢量在数据表中重新着色方块。下面显示了一个不起作用的简单示例。我知道您可以根据数值对单元格和文本进行着色,但我需要提供准确的颜色。任何帮助将不胜感激。
libarry(DT)
# set the colors for each box
mycolors = c("dodgerblue2","grey","firebrick2")
# recolor entire row (works)
DT::datatable(data.frame(src=c(1,2,3),tgt=c("█" ,"█" ,"█")),escape=F) %>%
formatStyle(columns = 1, color = "red") %>%
formatStyle(columns = 2, color = "blue")
# recolor based on mycolors (doesn't work)
DT::datatable(data.frame(src=c(1,2,3),tgt=c("█" ,"█" ,"█")),escape=F) %>%
formatStyle(columns = 1, color = "red") %>%
formatStyle(columns = 2, color = mycolors)
答案 0 :(得分:0)
这是一个解决方案:
dat <- data.frame(src=c(1,2,3), tgt=c("█", "█", "█"))
mycolors <- c("dodgerblue2", "grey", "firebrick2")
rgbcolors <- apply(grDevices::col2rgb(mycolors), 2,
function(rgb) sprintf("rgb(%s)", paste(rgb, collapse=",")))
column <- 2
jscode <- paste("function(row, data, index) {",
sprintf("var colors=%s;\n$(this.api().cell(index, %s).node()).css('color', colors[index]);",
sprintf("[%s]", paste(sprintf("'%s'", rgbcolors), collapse=", ")), column), "}", sep="\n")
datatable(dat, escape=FALSE,
options = list(rowCallback=JS(jscode))
)
rgbcolors
向量包含颜色的RGB定义,可用于html:
> rgbcolors
[1] "rgb(28,134,238)" "rgb(190,190,190)" "rgb(238,44,44)"
字符串jscode
是行回调的Javascript代码:
> cat(jscode)
function(row, data, index) {
var colors=['rgb(28,134,238)', 'rgb(190,190,190)', 'rgb(238,44,44)'];
$(this.api().cell(index, 2).node()).css('color', colors[index]);
}