jquerycssrshinylab-color-space

R shiny: color cell background based on Lab color space


I have a dataframe which contains Lab color space values. Here is an example:

L*     a*     b*       color
80     25     -30       NA
75     55     55        NA
30     0      25        NA
10     -20    30        NA
55     15     20        NA
60     43     18        NA
...  ...

Here are more than 1000 records. I would like to color the cells in the column color based on the Lab color space value in the L*,a*,b* columns. I have no background of the Jquery. I found an example here: R Shiny: table conditional formatting within renderUI but I do not know how to modify the Jquery script. Anyone can help me? Thank you!


Solution

  • You could do something like this if you were to color by rgb color space instead:

    library(shiny)
    
    color.min <- 0
    color.max <- 250
    n <- 100
    
    # Simulate data
    random.data <- data.frame("l"=runif(n,min=color.min,max=color.max),
                              "a"=runif(n,min=color.min,max=color.max),
                              "b"=runif(n,min=color.min,max=color.max),
                              "color"=rep(NA,n))
    
    server <- shinyServer(function(input, output, session) {
    
      observe({
        output$table <- renderTable({
          random.data
        })
      })
    })
    
    
    ui <- shinyUI(fluidPage(
      # Add jQuery script
      tags$head(
        tags$script(
          HTML("
              function color(){
                if(document.querySelector('#table')!=null){
                  // Select each table row in an array and loop over that with jQuery each
                  $('#table > table > tbody').find('tr').each(function(index, value) { 
                    // Get values for rgb and round to integers
                    var vals = [];
                    $(this).children('td').slice(1, 4).each(function(index, value) { 
                      vals[index] = parseInt( $(this).html() );
                    });
                    // Color 5:th child the selected rgb color
                    $(':nth-child(5)',this).css('background','rgb('+String(vals[0])+','+String(vals[1])+','+String(vals[2])+')');
                  })
                }
                else{
                  setTimeout(function() { color(); }, 100);
                }
              }
              color();
               ")
        )
      ),
      fluidRow(
        column(10, uiOutput("table")),
        column(2,actionButton("color","color"))
      )
    ))
    
    shinyApp(ui = ui, server = server)