Problems using ggvis in rMarkdown with variables

北城余情 提交于 2019-12-13 01:50: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.



来源:https://stackoverflow.com/questions/25476672/problems-using-ggvis-in-rmarkdown-with-variables

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!