我有一张桌子,我想做一个excel bargraph-like(What I want to do) 我有一个问题,负值不会反转图形(what I have now)。 正如你所看到的,我的值-5不是反向的,也不是比例的。 我想如果它是否定的我会反转吧。
我的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")
提前谢谢
答案 0 :(得分:2)
在这种情况下,您需要编写自己的颜色条功能。
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")