vlambda博客
学习文章列表

R语言笔记——图标可视化包之formattable




      本个专题将介绍R语言的一些基本技能和实用技巧。本教程说明了如何使用图标可视化包之formattable。





01

安装R包



# 一种从github安装install.packages("devtools")# 一种从CRAN网站安装install.packages("formattable")


02

加载R包



# 加载包library(formattable)


03

构建数据



df <- data.frame( id = 1:10, name = c("Bob", "Ashley", "James", "David", "Jenny",  "Hans", "Leo", "John", "Emily", "Lee"),  age = c(28, 27, 30, 28, 29, 29, 27, 27, 31, 30), grade = c("C", "A", "A", "C", "B", "B", "B", "A", "C", "C"), test1_score = c(8.9, 9.5, 9.6, 8.9, 9.1, 9.3, 9.3, 9.9, 8.5, 8.6), test2_score = c(9.1, 9.1, 9.2, 9.1, 8.9, 8.5, 9.2, 9.3, 9.1, 8.8), final_score = c(9, 9.3, 9.4, 9, 9, 8.9, 9.25, 9.6, 8.8, 8.7), registered = c(TRUE, FALSE, TRUE, FALSE, TRUE, TRUE, TRUE, FALSE, FALSE, FALSE),  stringsAsFactors = FALSE)


R语言笔记——图标可视化包之formattable

数据预览




df


# id name age grade test1_score test2_score final_score registered# 1 1 Bob 28 C 8.9 9.1 9.00 TRUE# 2 2 Ashley 27 A 9.5 9.1 9.30 FALSE# 3 3 James 30 A 9.6 9.2 9.40 TRUE# 4 4 David 28 C 8.9 9.1 9.00 FALSE# 5 5 Jenny 29 B 9.1 8.9 9.00 TRUE# 6 6 Hans 29 B 9.3 8.5 8.90 TRUE# 7 7 Leo 27 B 9.3 9.2 9.25 TRUE# 8 8 John 27 A 9.9 9.3 9.60 FALSE# 9 9 Emily 31 C 8.5 9.1 8.80 FALSE# 10 10    Lee  30     C         8.6         8.8        8.70      FALSE



R语言笔记——图标可视化包之formattable
R语言笔记——图标可视化包之formattable

# 指定表格可视化颜色

# age以渐变的形式呈现的

# grade中所有A背景为绿色.

# test1_score test2_score 以水平的柱状形式展示,背景:低分的为白色,高分的为粉色

# final_score 展示分值和等级,位于前三的字体显示为绿色,其他的为灰色

# registered 文本替换为yes或者no来展示






formattable(df, list( age = color_tile("white", "orange"), ## 白色到橘色渐变 grade = formatter("span", style = x ~ ifelse(x == "A",  style(color = "green", font.weight = "bold"), NA)), ## 如果为A就为绿色,字体为bold,否则不改变 area(col = c(test1_score, test2_score)) ~ normalize_bar("pink", 0.2), ## test1 和test2背景填充为粉色,并且以数值大小来表示柱子的长度 final_score = formatter("span", style = x ~ style(color = ifelse(rank(-x) <= 3, "green", "gray")), x ~ sprintf("%.2f (rank: %02d)", x, rank(-x))),  registered = formatter("span", style = x ~ style(color = ifelse(x, "green", "red")), x ~ icontext(ifelse(x, "ok", "remove"), ifelse(x, "Yes", "No")))))