rformattablehtmltoolswebshot

How to adjust row space in saved formattable table in R


With code below, I'm able to generate formattable table and save it as image:

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

Out:

enter image description here

Now I would like to go further to widen the line space between rows to keep aspect ratio of output image, for this example data, let's say I need to get the image's height larger than width.

To acheive that, which parameters should I change? I have adjusted the values in r, fig.width=9, fig.height=15, echo=FALSE, width = "100%", height = "16px", vwidth = 900, vheight = 1200, it's not working, anyone could help?


Solution

  • Try css style:

    formattable(mtcars, list(mpg = formatter("span",
            style = x ~ style("line-height" = "6em", color = ifelse(x > median(x), "red", NA)))))