在带有变量的rMarkdown中使用ggvis的问题

时间:2014-08-24 21:51:25

标签: r-markdown ggvis

你有几个问题

a)创建正确的文本以将变量传递给ggvis - 甚至不确定aes_string是否适用

b)绘图在浏览器中传播,而不是在rmarkdown文档中进行渲染

这是一个例子

---
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 个答案:

答案 0 :(得分:2)

这应该这样做:

---
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')
```

它有点复杂,因为您需要NULL检查类别,并且您需要明确告诉knitr在页面上放置ggvis输出。