0

下面的代码创建了一个小表。我不清楚如何进行这些更改:

1) 两个条之间的空白较少。使用 Inspect Element 我可以在 .table>tfoot>tr>td 中将填充从 8px 更改为 3px。这是正确的方法吗?如果是这样,如何将适当的 css 添加到我的 R 脚本中?

2) 去除彩条的圆角。同样,检查元素显示,如果我更改每个单元格的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")
4

2 回答 2

3

color_bar来自formattable包,但好消息是您可以定义自己的color_bar函数(只需color_bar在您的 R 控制台中输入将给您的源代码,color_bar然后您可以修改它)。它将解决您的问题2和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。

于 2018-04-03T00:46:38.517 回答
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()
于 2018-03-31T21:56:55.453 回答