基于此处的解决方案,向数据表添加颜色 我正在尝试制作一个 RAG 表并想要分配四种颜色。
library(tidyverse)
library(DT)
rag_df <- data.frame(Vulnerabilities = c("AB", "BC", "DE",
"FG", "HU", "JK",
"PF", "IC", "EC"),
`Rates` = c(21.1, 32.2, 2.12, 4.6, 5.43, 6.56, 7.9, 8.11, 9.13),
`Turns` = c(111, 222, 333, 444, 555, 666, 777, 88, 99))
high_rates <- rag_df$`Rates`
transmis_chanls <- rag_df$`Turns`
# Generate colors
color_intervals <- seq(0, 1, length.out = nrow(rag_df))
clrs_rmp <- colorRamp(c("#FD015B", "#FF7300", "#FFF200", "#A5D700"))(color_intervals)
# Extract RGB values
clrs_df <- tibble(r = clrs_rmp[, 1] / 255, g = clrs_rmp[, 2] / 255, b = clrs_rmp[, 3] / 255) %>%
mutate(mycolor=paste0("rgb(", paste(r,g,b,sep = ","),")"))
(clrs <- pull(clrs_df,mycolor))
# Apply colors to the datatable
create_db <- datatable(rag_df, rownames = TRUE) %>%
formatStyle(names(rag_df), backgroundColor = styleInterval(high_rates, clrs))
create_db
错误:
Error in styleInterval(high_rates, clrs) :
length(cuts) must be equal to length(values) - 1
三个问题:
1:您的切割向量(high_rates)必须按升序排序
high_rates <- sort(rag_df$`Rates`)
2:“cuts”的长度必须比
styleInterval
函数中“values”的长度小1。一种方法是将 color_intervals 序列的长度加 1:
color_intervals <- seq(0, 1, length.out = nrow(rag_df) + 1)
3:“formatStyle”函数的“backgroundColor”参数不喜欢[0,1]中的rbg值。所以除以 255。
clrs_df <- tibble(r = clrs_rmp[, 1],
g = clrs_rmp[, 2],
b = clrs_rmp[, 3]) %>%
mutate(mycolor=paste0("rgb(", paste(r,g,b,sep = ","),")"))
进行这些更改后,您应该得到以下图片: