我有一列是另外两列的总和。我尝试使用两种颜色的|
格式化程序,每种颜色代表单个数字。我尝试通过添加另一个color_bar
来扩充彩条代码。这个想法是大棒将是总和列。然后,我只需要另一个酒吧作为单个数字之一,我的酒吧有两种颜色。
一些问题:主要是,当我在color_bar
之前删除变量并将列放在宽度块中时,R似乎并不理解该引用。二,当我试图看看是否可以有两个颜色块时,通过调整第二个块的高度,只显示第二个块。我已将代码放在下面。
如果有人有任何提示,想法或解决方案,请告诉我。我可以使用其他想法来显示两个列的总和如何与总列相加。在我打字的时候,也许是一个馅饼迷你线?
以下是代码:
~
答案 0 :(得分:3)
我想暂时做同样的事情,所以这里至少有一个解决方案。不是试图让formattable()识别两个或多个单独的列,而是将相关列连接成单个字符变量。然后各种CSS和格式化函数相应地解析这些字符串。
这里的最大宽度是硬编码的(= 300px),所以你可能想要做出反应。
library(dplyr) # (>= 0.7.0)
library(formattable)
library(glue)
library(stringr)
library(tidyr)
library(scales)
set.seed(1234)
df <- data.frame(month = month.name[1:12],
valx = runif(12, 0, 5),
valy = runif(12, 2, 7))
df$total <- df$valx + df$valy
extr <- function(v, n, size = 6){
str_split_fixed(v, "_", size)[,n] %>% as.double
}
lblue <- csscolor(col2rgb("lightblue"))
lgray <- csscolor(col2rgb("lightgray"))
df %>% mutate(orders = row_number()) %>%
mutate_if(is.double, funs(lbl = round(., 0))) %>%
gather(key = item, value = score, valx:total) %>%
mutate(score = rescale(score, to = c(0,300)),
score = round(score, 0),
item = factor(item, levels = c("valx", "valy", "total"))) %>%
spread(key = item, value = score) %>%
arrange(orders) %>%
mutate(vals = str_c(valx, "_", valy, "_", total, "_", valx_lbl, "_",
valy_lbl, "_", total_lbl)) %>%
select(month, vals) %>%
formattable(align = "l", list(
vals = formatter("span",
style = x ~ style(
display = "inline-block",
direction = "ltr",
"border-radius" = "4px",
"padding-right" = "2px",
"text-indent" = str_c(extr(x,1)-10, "px"),
"background-image" = glue("linear-gradient(to right,
{lgray}, {lgray}), linear-gradient(to right, {lblue}, {lblue})"),
"background-repeat" = "no-repeat",
"background-position" = str_c("0 0, ", extr(x,1), "px 0"),
"background-size" = str_c(extr(x,1), "px 100%, ", extr(x,2), "px 100%"),
"width" = str_c(extr(x,3), "px"),
"text-align" = "left",
"position" = "relative"
), x ~ str_c(extr(x,4), " ", str_c(extr(x,5))))
))
CSS格式的灵感来自this answer。