如果 KableExtra/Formattable/dplyr 的值为负数,如何仅反转一个单元格中的一个条形图

how to reverse only one bar in one cell if the value is negative with KableExtra/Formattable/dplyr

我有一个 table,我想做一个 excel 条形图 (What I want to do) 我对不反转图形的负值有疑问 (what I have now)。 如您所见,我的值 -5 不是反向的,也不是正比的。 我想如果它是负面的,我会反转酒吧。

我的 csv 数据库

csv database

我的代码:

library(knitr)
library(kableExtra)
library(formattable)
library(dplyr)
library(stringr)

dat = read.csv("/dat.csv", header = TRUE, sep =';')

dat[] %>%
  mutate(
    KP1 = color_bar("lightgreen")(KP1),
    KP2 = color_bar("lightgreen")(KP2),
    KP3 = color_bar("lightgreen")(KP3),
    Exposure.1 = color_bar("lightgreen")(Exposure.1),
    Exposure.2 = color_bar("lightgreen")(Exposure.2),
    KP4 = color_bar("lightgreen")(KP4),
    KP5 = color_bar("lightgreen")(KP5)

  ) %>%
  kable("html", escape = F) %>%
  kable_styling("hover", full_width = F) %>%
  column_spec(5, width = "10cm") %>%
  column_spec(1,color = 'black', bold = T, border_right = T) %>%
  column_spec(1:5,width = "12.5%") %>%
  row_spec(2,extra_css = "border-top = 10px")

提前致谢

在这种情况下,您需要自己编写颜色条函数。

library(kableExtra)
library(dplyr)

cb <- function(x) {
  range <- max(abs(x))
  width <- round(abs(x / range * 50), 2)
  ifelse(
    x > 0,
    paste0(
      '<span style="display: inline-block; border-radius: 2px; ', 
      'padding-right: 2px; background-color: lightgreen; width: ', 
      width, '%; margin-left: 50%; text-align: left;">', x, '</span>'
    ),
    paste0(
      '<span style="display: inline-block; border-radius: 2px; ', 
      'padding-right: 2px; background-color: lightpink; width: ', 
      width, '%; margin-right: 50%; text-align: right; float: right; ">', x, '</span>'
    )
  )
}

dt <- data.frame(
  A = 1:10,
  B = -5:4
)

dt %>%
  mutate(
    A = cb(A),
    B = cb(B)
  ) %>%
  kable(escape = F) %>%
  kable_styling("hover", full_width = F) %>%
  column_spec(1:2, width = "3cm") %>%
  row_spec(0, align = "c")