我在这里打开了一个关于如何在数据表中添加范围栏的线程:以编程方式对数据表中的数字列进行颜色格式 https://stackoverflow.com/questions/54943418/programmatically-color-format-numeric-columns-in-a-datatable.
然而,我不想根据整个数据框拟合范围,而是想根据每个单独列的范围进行格式化。我找到了一些可行的代码,但是,它绝对是令人畏惧的并且不是编程性的。
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')
下面是为数据集中的每个数字列绘制它的开始。您可以修改以适应特定的用例。
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")
测试它与iris
and mtcars
数据集。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)