如何在R中捕获html输出为png

时间:2016-01-28 08:50:46

标签: r png htmlwidgets networkd3

我在R中使用networkD3包创建的交互式输出。我知道如何将输出保存为html页面,但我还需要将图表的“静态”版本保存为.png文件。

代码如下所示:

# Load package
library(networkD3)

# Create fake data
src <- c("A", "A", "A", "A", "B", "B", "C", "C", "D")
target <- c("B", "C", "D", "J", "E", "F", "G", "H", "I")
networkData <- data.frame(src, target)

# Plot
simpleNetwork(networkData)

我可以通过点击“导出”然后“另存为图像”来保存输出。但是,我更喜欢在代码中使用一些命令来保存图片。

2 个答案:

答案 0 :(得分:3)

我使用了此页https://github.com/hafen/trelliscope/blob/master/R/thumb.R中的功能并试图简化它。

您需要从http://phantomjs.org/download.html安装PhantomJS并在环境变量中设置路径。

该函数看起来像这样(param p是html小部件,thumbName是新的.png文件的名称):

library(htmlwidgets)

widgetThumbnail <- function(p, thumbName, width = 1024, height = 768) {
  phantom <- findPhantom()

  success <- FALSE
  if(phantom == "") {
    message("** phantomjs dependency could not be found - thumbnail cannot be generated (run phantomInstall() for details)")
  } else {
    res <- try({
      ff <- paste0(thumbName, ".html")
      ffjs <- paste0(thumbName, ".js")

      # don't want any padding
      p$sizingPolicy$padding <- 0
      suppressMessages(saveWidget(p, ff, selfcontained = FALSE))

      js <- paste0("var page = require('webpage').create();
                    page.viewportSize = { width: ", width,", height: ", height," };
                    page.clipRect = { top: 0, left: 0, width: ", width,", height: ", height," };
                    page.open('", ff, "', function(status) {
                    console.log(\"Status: \" + status);
                    if(status === \"success\") {
                    page.render('", thumbName, ".png');
                    }
                    phantom.exit();
                    });")
      cat(js, file = ffjs)
      system2(phantom, ffjs)
    })
    if(!inherits(res, "try-error")) {
      success <- TRUE
    }
    if(!file.exists(paste0(thumbName, ".png"))) {
      success <- FALSE
    }
  }

  if(!success) {
    message("** could not create htmlwidget thumbnail... creating an empty thumbnail...")
  }
}

#' Get instructions on how to install phantomjs
#' @export
phantomInstall <- function() {
  message("Please visit this page to install phantomjs on your system: http://phantomjs.org/download.html")
}

# similar to webshot
findPhantom <- function() {

  phantom <- Sys.which("phantomjs")

  if(Sys.which("phantomjs") == "") {
    if(identical(.Platform$OS.type, "windows")) {
      phantom <- Sys.which(file.path(Sys.getenv("APPDATA"), "npm", "phantomjs.cmd"))
    }
  }

  phantom

}

它创建.js文件,它接收你的html小部件,捕获屏幕并将.js,.html和.png文件保存到活动目录中:

# Load package
library(networkD3)

# Create fake data
src <- c("A", "A", "A", "A", "B", "B", "C", "C", "D")
target <- c("B", "C", "D", "J", "E", "F", "G", "H", "I")
networkData <- data.frame(src, target)

# Plot
plot = simpleNetwork(networkData)

# Save html as png
widgetThumbnail(p = plot, thumbName = "plot", height = 500)

答案 1 :(得分:3)

只是更新可能的解决方案。有一个名为webshot的软件包(由W. Chang等人提供),可以进行渲染并获取html页面的屏幕截图。

例如用法:

webshot::webshot("file.html")

要获取html文件,您可能需要查看R. Vaidyanathan等人的htmlwidgets::saveWidget

完全可重现的示例(在当前工作目录中保存simpleNetwork.png

library(networkD3)

src <- c("A", "A", "A", "A", "B", "B", "C", "C", "D")
target <- c("B", "C", "D", "J", "E", "F", "G", "H", "I")
networkData <- data.frame(src, target)

sn <- simpleNetwork(networkData)
saveNetwork(sn, "sn.html")

library(webshot)
webshot("sn.html", "simpleNetwork.png")

enter image description here