Search code examples
rshinyr-markdownggvis

Cannot render ggvis plot in Shiny app using Rmarkdown


I'm having a tough time getting ggvis and shiny to play nicely in an Rmarkdown-based application. I'm able to create the following ggvis figure with no problem even without using bind_shiny and ggvisOutput (as seen here):

---
title: "test"
runtime: shiny
output: html_document
---

```{r setup, include=FALSE}
require(ggvis)
knitr::opts_chunk$set(echo = TRUE)
```

```{r static}
inputPanel(
  sliderInput('n', 'n:', min = 10, max = 100, value = 50),
  actionButton('run', 'Run!')
)

data = data.frame(x = rnorm(50))

data %>%
  ggvis(~x) %>%
  layer_histograms()
```

However, I'm building dynamic reports to allow users to configure the input data and then re-execute by hitting a 'run' button, like this:

```{r config}
inputPanel(
  sliderInput('n', 'n:', min = 10, max = 100, value = 50),
  actionButton('run', 'Run!')
)

data = eventReactive(input$run, { data = data.frame(x = rnorm(input$n)) })

data %>%
  ggvis(~x) %>%
  layer_histograms()
```

When I try to run the document I get the nondescript error, Quitting from lines 26-36 (test.Rmd). Anyone know how to get this working?

UPDATE:

This almost works, but when I hit 'Run!' the ggvis plot renders in a separate browser window instead of in the document:

```{r config}
inputPanel(
  sliderInput('n', 'n:', min = 10, max = 100, value = 50),
  actionButton('run', 'Run!')
)

data = eventReactive(input$run, { data = data.frame(x = rnorm(input$n)) })

renderTable({summary(data())})

renderPlot({
  data() %>%
    ggvis(~x) %>%
    layer_histograms() %>%
    bind_shiny('plot')

})

ggvisOutput('plot')
```

Solution

  • The two questions you've linked to show you need the 'ggvis' code inside a reactive({, not a renderPlot({

    This now works for me

    ---
    title: "test"
    runtime: shiny
    output: html_document
    ---
    
    ```{r config}
    library(ggvis)
    inputPanel(
      sliderInput('n', 'n:', min = 10, max = 100, value = 50),
      actionButton('run', 'Run!')
    )
    
    data = eventReactive(input$run, { data = data.frame(x = rnorm(input$n)) })
    
    renderTable({summary(data())})
    
    reactive({
      data() %>%
        ggvis(~x) %>%
        layer_histograms() %>%
        bind_shiny('plot')
    
    })
    
    ggvisOutput('plot')
    ```