Search code examples
rggvis

Is there any alternative method to export ggvis to PNG, rather than export_png()?


I was wondering if somebody knows any alternative method to export ggvis objects to PNG. Can be implemented on Linux or Windows.

Thanks


Solution

  • I found several ways, I'm posting the one that is more straight forward.

    Required Libraries

    library(ggvis)
    library(XML)
    library(webshot)
    library(htmltools)
    

    Generating the ggvis and printing the HTML local directory

    outfile <- mtcars %>% ggvis(~wt, ~mpg) %>% layer_smooths() %>% set_options(width = 1200, height = 800)  %>% view_static() %>% html_print( background = "white", viewer = getOption("viewer", utils::browseURL))
    

    Parsing the HTML to a character vector

    webst <- htmlParse(outfile, asText=FALSE)
    showMethods(class=class(webst), where=search())
    webst <- as(webst, "character")
    class(webst)
    

    Using regular expressions to search for the name of the SVG object inside the HTML code / Generating the HTML Selector

    id <- webst %>% sub(pattern = "-container.*", replacement ="") %>% sub(pattern = ".*plot_", replacement ="") 
    selec <- paste0("#plot_", id, " > div > svg")
    

    Using Webshot to capture a screenshot of the browser.

    webshot(outfile, "test_webshot8.png",  selector = selec)
    

    Output

    enter image description here

    If you have suggestions how to simplify or a better method will be appreciated.