问题
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