R语言formattable表格按行奇偶修改Average列color_bar颜色
要实现Average列按行自定义条形颜色,你可以直接在formattable的列格式化规则中加入条件判断,通过行号或者指标名称匹配对应颜色,具体修改方案如下:
首先新增自定义蓝色变量,然后修改Average列的格式化逻辑即可,完整可运行代码如下:
library(data.table) library(dplyr) library(formattable) library(tidyr) customGreen0 = "#DeF7E9" customGreen = "#71CA97" customRed = "#ff7f7f" # 新增自定义蓝色 customBlue = "#4287f5" austinData= fread('https://raw.githubusercontent.com/lgellis/MiscTutorial/master/Austin/Imagine_Austin_Indicators.csv', data.table=FALSE, header = TRUE, stringsAsFactors = FALSE) attach(austinData) i1 <- austinData %>% filter(`Indicator Name` %in% c('Prevalence of Obesity', 'Prevalence of Tobacco Use', 'Prevalence of Cardiovascular Disease', 'Prevalence of Diabetes')) %>% select(c(`Indicator Name`, `2011`, `2012`, `2013`, `2014`, `2015`, `2016`)) %>% mutate (Average = round(rowMeans( cbind(`2011`, `2012`, `2013`, `2014`, `2015`, `2016`), na.rm=T),2), `Improvement` = round((`2011`-`2016`)/`2011`*100,2)) formattable(i1, align =c("l","c","c","c","r", "c", "l", "l", "r"), list( `Indicator Name` = formatter("span", style = ~ style(color = "grey",font.weight = "bold")), `2011`= color_tile(customGreen, customGreen0), `2012`= color_tile(customGreen, customGreen0), `2013`= color_tile(customGreen, customGreen0), `2014`= color_bar(customRed), `2015`= color_tile(customGreen, customGreen0), `2016`= color_bar(customGreen), # 修改Average列的格式化逻辑,按指标名称匹配颜色 `Average` = formatter("span", style = function(x, index) { cur_name <- i1$`Indicator Name`[index] bar_color <- ifelse(cur_name %in% c('Prevalence of Tobacco Use', 'Prevalence of Diabetes'), customBlue, customRed) style(display = "inline-block", `border-radius` = "5px", `padding-left` = "3px", `background-color` = csscolor(bar_color), width = percent(proportion(as.numeric(gsub(",", "", x))))) }) ))
以上实现用指标名称匹配颜色比按行号匹配更稳定,就算后续调整了i1的行顺序,颜色也不会匹配错误。如果习惯按行号匹配,只需要把bar_color的判断逻辑改成bar_color <- ifelse(index %in% c(2,4), customBlue, customRed)即可。
内容的提问来源于stack exchange,提问作者JK Lambert
相关产品推荐
相关产品推荐

