-->

Problems using ggvis in rMarkdown with variables

2019-08-04 12:27发布

问题:

Hi having a couple of problems

a) creating the correct text to pass variables to ggvis - not even sure aes_string is applicable

b) The plot propagates in browser rather than rendering in the rmarkdown document

Here is an example

---
title: "Untitled"
author: "pssguy"
date: "Sunday, August 24, 2014"
output: html_document
runtime: shiny
---
```{r, echo = FALSE, message=FALSE}
library(ggplot2)
library(ggvis)
library(dplyr)

selectInput("category3", "Choose Dataset:", c("mpg", "disp", "qsec"))

# ggplot renders correctly within renderPlot
  renderPlot({
   ggplot(mtcars,aes_string(input$category3,"disp"))+geom_point() 
  })

# ggvis works within document with hard coded info
   mtcars %>% ggvis(~wt,~disp)


mtcars %>% ggvis(aes_string(paste("~",input$category3,","),"~disp"))
#Operation not allowed without an active reactive context. (You tried to do something     that can only be done from inside a reactive expression or observer.)


# This needs correcting anyways
renderPlot({
   mtcars %>% ggvis(aes_string(paste("~",input$category3,","),"~disp"))
 })
# <text>:1:7: unexpected ',' 1: ~ mpg ,


# even if the above is corrected the plot opens in a browser rather than the document
renderPlot({
 mtcars %>% ggvis(~wt,~disp)
  })
```

TIA

回答1:

This should do it:

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

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

selectInput("category3", "Choose Dataset:", c("mpg", "disp", "qsec"))

# ggplot renders correctly within renderPlot
renderPlot({
  print(input$category3)
  ggplot(mtcars,aes_string(input$category3,"disp"))+geom_point()
})

# ggvis with dynamically changing columns
reactive({
  if (!is.null(input$category3))
    col <- input$category3
  else
    col <- "mpg"

  mtcars %>% ggvis(prop("x", as.name(col)), ~disp)

}) %>% bind_shiny('foo')

ggvisOutput('foo')
```

It's a little complicated because you need a NULL check for the category, and you need to explicitly tell knitr to put a ggvis output on the page.