0

我有一张桌子,我想做一个类似 excel 条形图的(我想做的)我有一个不反转图表的负值问题(我现在拥有的)。如您所见,我的值 -5 不是反向的,也不是成比例的。我想如果它是负面的,我会反转酒吧。

我的 csv 数据库

.csv 数据库

我的代码:

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")

先感谢您

4

1 回答 1

4

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

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")

例子

于 2018-04-19T15:46:57.147 回答