下面的代码会创建一个小表。 我不清楚如何进行这些改变:
1)两个条之间的空白较小。使用Inspect Element我可以在.table> tfoot> tr> td中将填充从8px更改为3px。这是正确的方法吗?如果是这样,我如何将相应的CSS添加到我的R脚本?
2)去除彩条的圆角。同样,inspect元素显示如果我更改border_radius:0px和padding-right:0px,则每个单元格都会发生更改。但同样,这似乎并不正确。
3)如何更改包含条形图的单元格中文本字体的颜色?
library(formattable)
library(kableExtra)
library(knitr)
fraction <- function(x, df) {
x/df$count
}
df <- tibble (
Type = c("A", "B", "C"),
count = c(500, 350, 860),
Decreasing = c(226, 103, 507),
Increasing = c(300, 250, 350)
)
mutate(df,
Decreasing = color_bar(color = "lightgrey", fun = "fraction", df)(Decreasing),
Increasing = color_bar(color = "lightgreen", fun = "fraction", df)(Increasing)
) %>%
select(Type, Decreasing, Increasing) %>%
kable("html", escape = "F", align = c("l", "r", "l")) %>%
kable_styling(bootstrap_options = c("striped", "hover", "responsive"), full_width = F, position = "float_left")
答案 0 :(得分:3)
color_bar
来自formattable
软件包,但好消息是您可以定义自己的color_bar
函数(只需在R控制台中键入color_bar
即可源代码color_bar
,然后您可以修改它)。它将解决您的问题2&amp; 3.
color_bar2 <- function (color = "lightgray", fun = "proportion", ...)
{
fun <- match.fun(fun)
formatter(
"span",
style = function(x) style(
display = "inline-block",
direction = "rtl", `border-radius` = "0px", `padding-right` = "2px",
`background-color` = csscolor(color), color = csscolor("red"),
width = percent(fun(as.numeric(x), ...))))
}
mutate(df,
Decreasing = color_bar2(color = "lightgrey", fun = "fraction", df)(Decreasing),
Increasing = color_bar2(color = "lightgreen", fun = "fraction", df)(Increasing)
) %>%
select(Type, Decreasing, Increasing) %>%
kable("html", escape = "F", align = c("l", "r", "l")) %>%
kable_styling(bootstrap_options = c("striped", "hover", "responsive"), full_width = F, position = "float_left")
对于问题1,如果您要在rmarkdown中呈现表格,请查看此页面https://rmarkdown.rstudio.com/html_document_format.html#custom_css,了解如何在rmarkdown中使用custom_css。
答案 1 :(得分:0)
如果你不介意另一个包(我自己的):
library(tibble)
library(dplyr)
library(huxtable)
df <- tibble (
Type = c("A", "B", "C"),
count = c(500, 350, 860),
Decreasing = c(226, 103, 507),
Increasing = c(300, 250, 350)
)
ht <- as_hux(df)
ht %>%
select(Type, Decreasing, Increasing) %>%
set_all_padding('3px') %>%
set_text_color(everywhere, 2:3, "red") %>%
add_colnames()
但这并不能让你获得彩条。 (嗯,也许我应该添加一个函数。)你可以通过......那样的东西:
my_color_bar <- color_bar(color = "lightgrey", fun = "fraction", df)
ht %>%
select(Type, Decreasing, Increasing) %>%
set_all_padding('3px') %>%
set_text_color(everywhere, 2:3, "red") %>%
set_escape_contents(everywhere, 2:3, TRUE) %>%
set_number_format(everywhere, 2:3, list(my_color_bar)) %>%
add_colnames()