1

使用下面的代码,我可以生成可格式化的表格并将其保存为图像:

library(formattable)
library(htmltools)
library(webshot2)

df <- data.frame(
  id = 1:10,
  name = c("Bob", "Ashley", "James", "David", "Jenny", 
           "Hans", "Leo", "John", "Emily", "Lee"), 
  age = c(28, 27, 30, 28, 29, 29, 27, 27, 31, 30),
  grade = c("C", "A", "A", "C", "B", "B", "B", "A", "C", "C"),
  Test.number.1.score = c(8.9, 9.5, 9.6, 8.9, 9.1, 9.3, 9.3, 9.9, 8.5, 8.6),
  test2_score = c(9.1, 9.1, 9.2, 9.1, 8.9, 8.5, 9.9, 9.3, 9.1, 8.6),
  final_score = c(9, 9.3, 9.4, 9, 9, 8.9, 9.25, 9.6, 8.8, 8.7),
  registered = c(TRUE, FALSE, TRUE, FALSE, TRUE, TRUE, TRUE, FALSE, FALSE, FALSE),
  stringsAsFactors = FALSE)

dt <- formattable(df)

export_formattable <- function(f, file, 
                               width = "100%", height = "16px",
                               background = "white", delay = 0.2)
    {
      w <- as.htmlwidget(f, width = width, height = height)
      path <- html_print(w, background = background, viewer = NULL)
      url <- paste0("file:///", gsub("\\\\", "/", normalizePath(path)))
      webshot(url,
              vwidth = 900, vheight = 1200, 
              file = file,
              selector = ".formattable_widget",
              delay = delay)
}
export_formattable(dt,'./data.png')

出去:

在此处输入图像描述

现在我想进一步扩大行之间的行间距以保持输出图像的纵横比,对于这个示例数据,假设我需要让图像的高度大于宽度。

为了实现这一点,我应该更改哪些参数?我已经调整了 , , 中的值,r, fig.width=9, fig.height=15, echo=FALSE它不起作用,有人可以帮忙吗?width = "100%", height = "16px"vwidth = 900, vheight = 1200

4

1 回答 1

1

尝试css风格:

formattable(mtcars, list(mpg = formatter("span",
        style = x ~ style("line-height" = "6em", color = ifelse(x > median(x), "red", NA)))))
于 2021-10-19T23:15:21.683 回答