0

我尝试使用此链接中的代码绘制带有图形的表格:

library(sparkline)
library(tidyverse)
library(formattable)
library(kableExtra)
library(shiny)
library(htmltools)
library(webshot2)

df <- data.frame(stringsAsFactors=FALSE,
             V1 = c("country", "A", "B", "C"),
             V2 = c(2000L, 100L, 600L, 50L),
             V3 = c(2001L, 200L, 500L, 60L),
             V4 = c(2002L, 300L, 400L, 70L),
             V5 = c(2003L, 400L, 300L, 80L),
             V6 = c(2004L, 500L, 200L, 90L),
             V7 = c(2005L, 600L, 100L, 100L)
)

df.names <- df[1,]
names(df) <- df.names
df <- df[-1,]

graph <- df %>% 
  group_by(country) %>% 
  gather(key=year, value=value, -country) %>% 
  summarise(graph=spk_chr(
    value, 
    chartRangeMin = 0,
    type="line"))

df2 <- left_join(df, graph, by=c("country"))

dt <- df2 %>%
formattable::format_table(
  x = .,
  formatters = list(
    align=c("l")
  )
) %>%
  kable_styling("striped", full_width = F) %>%
  group_rows("group1", 1, 2) %>%
  group_rows("group2", 3,3) %>%
  htmltools::HTML() %>%
  shiny::div() %>%
  sparkline::spk_add_deps()

出去:

在此处输入图像描述

另存为图像的代码:

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 = 1600, vheight = 900, 
              file = file,
              selector = ".formattable_widget",
              delay = delay)
}
export_formattable(dt,"./res.png")

但是当我将结果保存为图像时,它会引发一个错误:Error in UseMethod("as.htmlwidget") : no applicable method for 'as.htmlwidget' applied to an object of class "shiny.tag",它适用于没有折线图的表格。

任何人都可以帮助我实现这一目标吗?谢谢。

4

0 回答 0