Search code examples
htmlrplotdata-visualizationggvis

Save ggvis html to file


Goal:

I would like to be able to create static ggvis plots and pass a parameter for a directory path where the html file is saved.

Mock Data:

require(ggvis)

# Create mock data to work with
dfa <- data.frame(
date_a = seq(from= as.Date("2015-06-10"), 
    to= as.Date("2015-07-01"), by= 1),
val_a = c(2585.150, 2482.200, 3780.186, 3619.601, 
    0.000, 0.000, 3509.734, 3020.405, 
    3271.897, 3019.003, 3172.084, 0.000, 
    0.000, 3319.927, 2673.428, 3331.382, 
    3886.957, 2859.887, 0.000, 0.000, 
    2781.443, 2847.377) )

Example plot:

Here is an example of a static ggvis plot.

# Create working static ggvis plot
dfa %>%
  ggvis( x= ~date_a , y= ~val_a, stroke := "black", opacity := 0.5 ) %>% 
    scale_datetime("x", nice = "month", domain = c(as.Date("2015-06-10"),
    as.Date("2015-07-15") )) %>%
    layer_lines() %>% layer_points( fill := "black" )

When this is run, by default the html file is written to "file:///C:/Users/.../AppData/Local/Temp/RtmpyuMDDO/viewhtml1bf039815bb2/index.html". Instead, I would like to be able to pass a desired path: "file:///C:/my/desired/path/to/plot/index.html" as a parameter and have the html file saved there.

Research:

Here are some related topics that I have read but was not able to make work:

Documentation

SO Discussion on saving html

With respect to the previous SO discussion, first has there been further development since this older post, and second, I would prefer to just pass a destination path and have the html written to the specified path.


Solution

  • Put this into output.Rmd:

    ```{r, echo=FALSE}
    library(ggvis)
    dfa <- data.frame(
    date_a = seq(from= as.Date("2015-06-10"),
        to= as.Date("2015-07-01"), by= 1),
    val_a = c(2585.150, 2482.200, 3780.186, 3619.601,
        0.000, 0.000, 3509.734, 3020.405,
        3271.897, 3019.003, 3172.084, 0.000,
        0.000, 3319.927, 2673.428, 3331.382,
        3886.957, 2859.887, 0.000, 0.000,
        2781.443, 2847.377) )
    
    dfa %>%
      ggvis( x= ~date_a , y= ~val_a, stroke := "black", opacity := 0.5 ) %>%
        scale_datetime("x", nice = "month", domain = c(as.Date("2015-06-10"),
        as.Date("2015-07-15") )) %>%
        layer_lines() %>% layer_points( fill := "black") %>% 
      knit_print.ggvis(inline=TRUE)
    ```
    

    At an R console (in the proper directory), run:

    rmarkdown::render("output.Rmd")
    

    And output.html will look like:

    enter image description here

    and be a standalone document.

    If you work a bit, you can make this a function that does what you need.