【问题标题】:Problems using ggvis in rMarkdown with variables在带有变量的 rMarkdown 中使用 ggvis 的问题
【发布时间】:2014-08-24 21:51:25
【问题描述】:

您好,有几个问题

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

【问题讨论】:

    标签: r-markdown ggvis


    【解决方案1】:

    应该这样做:

    ---
    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 输出放在页面上。

    【讨论】:

    • 谢谢温斯顿。如何避免发布时出现反应文本? echo=FALSE 删除其他代码,但不删除该部分
    • 关于我的最后一条评论,似乎将反应切换到观察函数并将 %>% bind_shiny('foo') 放在函数的末尾而不是外部解决了这个问题
    • 这个答案帮了我很多忙。谢谢温斯顿。
    猜你喜欢
    • 1970-01-01
    • 2017-04-14
    • 2021-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-21
    • 1970-01-01
    • 2014-09-16
    相关资源
    最近更新 更多