通过数据表中的每个列范围以编程方式设置颜色格式的数字列 [英] Programmatically Color Format Numeric Columns by Each Column Range in Datatable
本文介绍了通过数据表中的每个列范围以编程方式设置颜色格式的数字列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在这里打开了一个有关如何在数据表中添加范围条的线程:
解决方案
从开始为数据集中的每个数字列绘制图表。您可以修改以适合特定的用例。
库(tidyverse)
库(DT)
库(RColorBrewer)
colorbarTable = function(table,colorscale){
num = sapply(table,is.numeric)#查找哪些列为数字
colors = brewer。 pal(sum(num),colorscale)#定义颜色数量
DT = datatable(table,filter ='top',options = list(pageLength = 5,autoWidth = TRUE))#定义基本数据表
for(i in seq_along(num)){
if(num [i]){
#如果将数值加到数据表
DT = DT%>%
formatStyle(names(table)[i],
background = styleColorBar(range(table [,i]),colors [i]),
backgroundSize =' 98%88%',
backgroundRepeat ='不重复',
backgroundPosition ='center')
}
}
return(DT)
}
colorbarTable(mtcars, Pastel1)
使用 iris
和 mtcars
数据集进行了测试。 / p>
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')
解决方案
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.
这篇关于通过数据表中的每个列范围以编程方式设置颜色格式的数字列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文