首页 > 解决方案 > R Formattable -> 导出的 .png 和导出的 html 小部件不匹配

问题描述

我正在使用此代码导出格式化表格的 .png 和 HTML 版本。

.png 出来很好(表格应该是什么样子),但 HTML 导出看起来像这样,即使它在查看器窗格中很好:https ://rpubs.com/Drewnonymous/739404

第二个不那么重要的问题是我也很想摆脱 NA,但我所做的每一种方式都搞砸了表格,或者删除了数字格式。

在 20 多年没有编码之后(从大学开始),我对这一切还是很陌生,所以请温柔一点。我仍然处于“从别人那里借用代码并试图弄清楚它是如何工作以及为什么工作的阶段”。

非常感谢任何和所有帮助。

percent_change_formatter1 <- 
  formatter("span", 
            style = x ~ formattable::style(
              font.weight = ifelse(x>0 | x<0, "bold", ""),
              color = ifelse(x > 0, customGreen, ifelse(x < 0, customRed, "black"))),
            x ~ icontext(ifelse(x>0, "arrow-up", "arrow-down"), x)
  )
percent_change_formatter2 <- 
  formatter("span", 
            style = x ~ formattable::style(
              font.weight = ifelse(x>0 | x<0, "bold", ""), 
              color = ifelse(x < 0, customGreen, ifelse(x > 0, customRed, "black"))),
            x ~ icontext(ifelse(x>0, "arrow-up", "arrow-down"), x)
  )


i_tcp <- formattable(i_tcp, align =c("c","r","l","r","l","r","l"),
                     list(
  `7-day averages for USA` = formatter("span", style = ~ style(color = "grey",font.weight = "bold")), 
  `Tests`= color_bar(customGreen0, proportion, 1),
  ` % chng.`= percent_change_formatter1,
  `New cases`= color_bar(CustomOrange0, proportion, 1),
  `% chng. `= percent_change_formatter2,
  `% positive`= color_bar(CustomPink0, proportion, 1),
  `% chng.`= percent_change_formatter2
))

export_formattable <- function(f, file, width = 690, height = 330, background = "", 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,
          file = file,
          selector = ".formattable_widget",
          delay = delay)
}

dir.create(paste(today), recursive = T)
setwd(paste(today))
export_formattable(i_tcp, paste(today, "_us_tcp_table.png"))
saveWidget(as.htmlwidget(i_tcp, width = 690, height = 330), paste(today,"_us_tcp_table.htm"), selfcontained = F, libdir = "libdir")
setwd("..")

标签: rhtmlwidgetsformattable

解决方案


推荐阅读