将 gvisGeoMap 对象保存为 png

Saving gvisGeoMap object to png

如何将 gvis 对象从 googleVis 保存到 png? ggvis 有 export_png,但这不适用于 googleVis。

看到好几个人问这个,真的没有办法吗?

test_data <- data.frame(count=c(1,2,5),group=c("Australia","Austria","China"))

p <- gvisGeoMap(test_data,locationvar='group',numvar='count',options=list(dataMode='regions',colors="['0x0000ff', '0xff0000']"))

plot(p)

有很多方法可以继续进行,但结果不可预知。 一些技巧:

  1. Xvfb、imagemagick 和浏览器。

    您需要安装所有这三个。这不适用于 Windows。我假设您已经安装了 xvfb 和 imagemagick。 您在 shell:-

    中启动 xvfb 服务器
    Xvfb :3 -screen 0 1024x768x24 &
    

    现在在 R 中, 您可以将文件打印为 html:

    print(p, file="p.html")
    

    现在系统调用:

    system("DISPLAY=:3      firefox     g1.html  &")
    

    现在打印文件使用:

    system("DISPLAY=:3 import -window root p.png")
    

    您将获得 p.png 的文件。您也可以使用其他浏览器,例如 chrome.

  2. 使用 wkhtmltopdf 包。

    安装 wkhtmltopdf 并将其放入您的 PATH 后,使用系统调用:

    print(p, file="p.html")
    system("wkhtmltoimage --enable-plugins --javascript-delay 10000   p.html p.png")
    

    结果不可预测。有时闪光灯不起作用。有时它适用于某些平台。我无法像我的第一个解决方案那样重现。 (对于 OP,此解决​​方案有效。这是一个跨平台解决方案。)

  3. 作为闪亮的应用程序,phantomjs 和 webshot:

    假设您已经打印了我提供的文件,请使用以下方法创建一个闪亮的应用程序:

    mkdir app # Create App Directory
    # Create UI
    cat <<- EOF > app/ui.R
    library(shiny)
    
    shinyUI(fluidPage(
      titlePanel("Google Chart"),
      mainPanel(
        includeHTML("../g1.html")
      )
    ))    
    EOF
    # Create server
    cat <<- EOF > app/server.R
    library(shiny)
    shinyServer(function(input, output) {
    })
    EOF
    

    现在安装phantomjs:

    npm install -g phantomjs
    

    在 r:-

    install.packages("webshot")
    appshot("app", "p.png")
    

    你会看到你不会得到 flash 图表,因为 phantomjs 现在不支持 flash。所以这种方法也有局限性。只有第一种方法有效,但它不是跨平台的。但是您可以在 windows 中使用等效的东西继续这种方法。

截至目前,webshot2 可用。我发布了我的解决方案 .