Programmatically Color Format Numeric Columns by Each Column Range in Datatable

旧时模样 提交于 2019-12-24 11:27:23

问题


I opened a thread about how to add range bars in a datatable here:Programmatically color format numeric columns in a datatable.

However instead of fitting the ranges based on the whole data frame, I would like to format based on the range of each individual column. I figured out some code that works, however, it is most definitely daunting and not programmatic.

library(magrittr)
library(DT)

# Specify numeric columns
foo <- sapply(iris, is.numeric)

datatable(iris, filter = 'top', options = list(pageLength = 5, autoWidth = TRUE)) %>%
  formatStyle(names(iris)[foo][1],
              background = styleColorBar(range(iris[, 1]), 'lightblue'),
              backgroundSize = '98% 88%',
              backgroundRepeat = 'no-repeat',
              backgroundPosition = 'center') %>%
  formatStyle(names(iris)[foo][2],
              background = styleColorBar(range(iris[, 2]), 'green'),
              backgroundSize = '98% 88%',
              backgroundRepeat = 'no-repeat',
              backgroundPosition = 'center')


回答1:


Heres a start which plots it for every numeric column in the dataset. You can modify is to fit a specific use case.

library(tidyverse)
library(DT)
library(RColorBrewer)

colorbarTable = function(table,colorscale){
  num = sapply(table,is.numeric) #Find which columns are numeric
  colors = brewer.pal(sum(num),colorscale) #Define the number of colors

  DT = datatable(table,filter = 'top',options = list(pageLength = 5, autoWidth = TRUE)) #Define the base data table

  for(i in seq_along(num)){
    if(num[i]){
      #If numeric add to the datatabls
      DT = DT%>%
        formatStyle(names(table)[i],
                    background = styleColorBar(range(table[,i]), colors[i]),
                    backgroundSize = '98% 88%',
                    backgroundRepeat = 'no-repeat',
                    backgroundPosition = 'center')
    }
  }

  return(DT)
}


colorbarTable(mtcars,"Pastel1")

Tested it with the iris and mtcars dataset.



来源:https://stackoverflow.com/questions/54950917/programmatically-color-format-numeric-columns-by-each-column-range-in-datatable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!