Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to give color to a given interval of rows of a DT table?

Tags:

r

shiny

I am using the DT library to visualize tables, but let's say I want to give a color to some rows like for example RED from row 1 to row 4:

enter image description here

Also it would be really nice to change the color of the text if it's possible. After hours of searching I found this function from library DT:

datatable(df, rownames = FALSE) %>%
  formatStyle(columns = "inputval", 
              background = styleInterval(c(0.7, 0.8, 0.9)-1e-6, c("white", "lightblue", "magenta", "white"))) 

But I need to give color to all columns not just a selected column like inputval in the code, can I give to columns value something like names(df) so it can give color to all columns? And styleInterval selects the values in table not the interval of rows, how can I do that so I can select the rows and give them a color?

like image 380
Programmer Man Avatar asked Aug 07 '17 08:08

Programmer Man


1 Answers

Something like this should do the job. Note that I coloured the rows 2:4 on purpose instead of 1:4 for more functionality:

library(shiny)
library(DT)

ui <- basicPage(
  mainPanel(DT::dataTableOutput('mytable'))
)

server <- function(input, output,session) {

  output$mytable = DT::renderDataTable(    
    DT::datatable(mtcars,  options = list(
      pageLength = 25,
      rowCallback = JS('function(row, data, index, rowId) {',
                       'console.log(rowId)','if(rowId >= 1 && rowId < 4) {',
                       'row.style.backgroundColor = "pink";','}','}')
    )
    )
  ) 




}
runApp(list(ui = ui, server = server))

enter image description here

Edit: Dynamically colour rows: here I simply used sub to substitute for the range to colour the rows

library(shiny)
library(DT)

fnc <- JS('function(row, data, index, rowId) {',
                    'console.log(rowId)','if(rowId >= ONE && rowId < TWO) {',
                    'row.style.backgroundColor = "pink";','}','}')

ui <- basicPage(
  sliderInput("colorrows", "Which to color:",min = 0, max = 10, value = c(1,3)),
  mainPanel(DT::dataTableOutput('mytable'))
)

server <- function(input, output,session) {

  Coloring <- eventReactive(input$colorrows,{
    fnc <- sub("ONE",input$colorrows[1],fnc)
    fnc <- sub("TWO",input$colorrows[2],fnc)
    fnc
  })

  output$mytable = DT::renderDataTable(
    DT::datatable(mtcars,  options = list(pageLength = 25,rowCallback = Coloring())
    )
  )
}
runApp(list(ui = ui, server = server))

enter image description here

like image 95
Pork Chop Avatar answered Oct 02 '22 03:10

Pork Chop