TheComeOnMan TheComeOnMan - 2 months ago 16
R Question

Interactive ggplot in Markdown

The examples on http://rmarkdown.rstudio.com/authoring_shiny.html indicate that

renderPlot
itself renders the plot to the markdown. How can we get our markdown to allow interactions such as clicks, brushes, etc. which are declared as part of the subsequent
plotOutput
step?

Interactivity examples with
plotOutput
in
shiny
here - http://shiny.rstudio.com/articles/plot-interaction.html.

Code snippet -

```{r, echo = FALSE}

output[['Plot1']] = renderPlot(

ggplot(mtcars) + geom_point(aes(x = cyl, y = qsec))

)

renderPlot(

ggplot(mtcars) + geom_point(aes(x = cyl, y = wt))

)


print("renderPlot above. plotOutput below (which doesn't get rendered).")

renderUI({
plotOutput(
'Plot1',
brush = brushOpts(
id = 'Brush1'
),
dblclick = dblclickOpts(id = 'DblClick1'),
click = 'Click1',
height = "100%"

)
})

```

Answer

The problem is that you're using the parameter height in plotOutput with percents. We can find in the documentation ?shiny::plotOutput:

Note that, for height, using "auto" or "100%" generally will not work as expected, because of how height is computed with HTML/CSS.

If you remove height = 100%, which is in this case redundant, the plot will be rendered. If you want to change the height of the output you can use pixels instead of percents.

Then you can access values via input$Click1, input$DblClick1 and input$Brush1 and pass them to render* functions.


Example:

---
title: "Example"
author: "Unnamed_User"
date: "24 Sep 2016"
output: html_document
runtime: shiny
---

```{r, echo = FALSE}
library(ggplot2)
```

### Normal plot

```{r, echo = FALSE} 
ggplot(mtcars) + geom_point(aes(x = cyl, y = wt))
``` 


### Interactive plot

```{r, echo = FALSE}
renderUI({
   plotOutput(
      'Plot1',
      brush = brushOpts(
         id = 'Brush1'
      ),
      dblclick = dblclickOpts(id = 'DblClick1'),
      click = 'Click1'
   )
})

output[['Plot1']] <- renderPlot({ 
   ggplot(mtcars) + geom_point(aes(x = cyl, y = qsec))
})
```

### Clicked point

```{r, echo = FALSE}
renderPrint({ 
  cat(" x:", input$Click1$x, 
      "\n",
       "y:", input$Click1$y)
})
```