Search code examples
rr-markdownggvis

How to embed ggvis interactive charts in RMarkdown?


I am trying to knit an RMarkdown into html this plot from the interactivity vignette:

mtcars %>% ggvis(x = ~wt) %>%
    layer_densities(
      adjust = input_slider(.1, 2, value = 1, step = .1, label = "Bandwidth adjustment"),
      kernel = input_select(
        c("Gaussian" = "gaussian",
          "Epanechnikov" = "epanechnikov",
          "Rectangular" = "rectangular",
          "Triangular" = "triangular",
          "Biweight" = "biweight",
          "Cosine" = "cosine",
          "Optcosine" = "optcosine"),
        label = "Kernel")
    )

But I get the following error message:

## Warning: Can't output dynamic/interactive ggvis plots in a knitr document.
## Generating a static (non-dynamic, non-interactive) version of the plot.

Solution

  • You must set "output: html_document" and "runtime: shiny" in the header. This works for me:

    ---
    title: "stackoverflow"
    author: "Kári S Friðriksson"
    date: "7 nóvember 2016"
    output: html_document
    runtime: shiny
    ---
    
    ```{r setup, include=FALSE}
    knitr::opts_chunk$set(echo = TRUE)
    library(ggvis)
    ```
    
    
    
    ```{r eruptions, echo=FALSE}
    mtcars %>% ggvis(x = ~wt) %>%
        layer_densities(
          adjust = input_slider(.1, 2, value = 1, step = .1, label = "Bandwidth adjustment"),
          kernel = input_select(
            c("Gaussian" = "gaussian",
              "Epanechnikov" = "epanechnikov",
              "Rectangular" = "rectangular",
              "Triangular" = "triangular",
              "Biweight" = "biweight",
              "Cosine" = "cosine",
              "Optcosine" = "optcosine"),
            label = "Kernel")
        )
    ```
    

    The easiest way to do this is to go to file/new file/R markdown/Shiny/Shiny document. Then the header will be automatically set up for you, and there will be a play button instead of the knitr button on the bar above the code box. Notice also that you need to include library(ggvis) in the code because shiny will start with a cleas slate and not be able to "see" the packages or functions that you have loaded.