【问题标题】:How to embed a ggvis chart from an external source in shiny?如何在闪亮中嵌入来自外部来源的ggvis图表?
【发布时间】:2016-07-10 22:50:00
【问题描述】:

我已经在Dynamic ggvis object in Shiny 获得了几乎相同主题的答案,但我仍然堆满了类似的代码,我真的不明白为什么。

ui.R

library(shiny)
library(ggvis)
shinyUI(fluidPage(

  fluidRow(titlePanel("My app")),

    fluidRow(
          column(3,
                 tags$h1('Menu'),
                 radioButtons('colors', label = 'select bars color',
                                    c("Red"='red','Green'='green','Blue'='blue'))
                 ),
          column(9,
                 tags$h1("hello"),
                 ggvisOutput('test1'),
                 tags$h2("Chosen color is",textOutput('testText', inline = T))
                 )
    )
   )
  )

server.R

library(shiny)
library(ggvis)
shinyServer(function(input, output) {
source("charts.R")
  output$testText <- reactive({ input$colors })
  input_color <- reactive({ input$colors })
  # cars %>%
  #   ggvis(~speed, fill:= input_color) %>%
  #   layer_bars() %>%
  #   bind_shiny("test1", "test1_ui")
  chart1() %>%
    bind_shiny("test1", "test1_ui")
})

charts.R

chart1 <- reactive({
  cars %>% 
    ggvis(~speed, fill:= input_color) %>% 
    layer_bars() 
})

我想将chart1 从charts.R 呼叫到server.R。如果我使用 server.R 中的注释代码,一切都适用于 ggvis,但当我尝试从 charts.R 调用 ggvis 函数时(如未注释的代码),一切都不起作用。

另外,您认为创建多个 .R 脚本是一种好习惯,还是我应该选择合适的模块?

【问题讨论】:

    标签: r shiny ggvis


    【解决方案1】:

    您需要在脚本中编辑两件事:

    1. 如果要将服务器或ui代码拆分成多个文件,可以使用source(local=TRUE)来加载每个文件。您可以将其视为将代码内联,因此来自源文件的代码将收到与您复制并粘贴文本相同的范围。 (无耻抄自here)

    2. 只能在其他反应式表达式或 render* 表达式中使用括号调用反应式对象

    所以,你的server.R 应该是这样的:

    library(shiny)
    library(ggvis)
    
    shinyServer(function(input, output) {
    
    source("charts.R", local = T)
    
    output$testText <- reactive({ input$colors })
    input_color <- reactive({ input$colors })
    
    chart1 %>%
    bind_shiny("test1", "test1_ui")
    
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-22
      • 1970-01-01
      • 1970-01-01
      • 2016-10-11
      • 1970-01-01
      • 1970-01-01
      • 2015-09-25
      • 1970-01-01
      相关资源
      最近更新 更多