【问题标题】:How to color text in a datatable based on a vector of colors using R DT Shiny?如何使用 R DT Shiny 基于颜色向量为数据表中的文本着色?
【发布时间】:2018-05-23 21:42:30
【问题描述】:

我正在开发一个 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)

【问题讨论】:

    标签: r datatables shiny dt


    【解决方案1】:

    这是一个解决方案:

    dat <- data.frame(src=c(1,2,3), tgt=c("&#9608;", "&#9608;", "&#9608;"))
    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]);
    }
    

    【讨论】:

    猜你喜欢
    • 2021-05-10
    • 2018-10-12
    • 1970-01-01
    • 2021-08-27
    • 2020-04-13
    • 2021-11-02
    • 2016-09-23
    • 1970-01-01
    • 2016-05-05
    相关资源
    最近更新 更多