如何从外部源嵌入ggvis图表闪亮?

时间:2016-07-10 22:50:01

标签: r shiny ggvis

我已经在这里找到了几乎相同主题的答案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.Rserver.R。如果我使用server.R中的注释代码,那么所有内容都适用于ggvis,但当我尝试从charts.R调用ggvis函数时(例如在未注释的代码中),它不会。

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

1 个答案:

答案 0 :(得分:1)

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

  1. 如果要将服务器或ui代码拆分为多个文件,可以使用source(local=TRUE)加载每个文件。您可以将此视为将代码放入内联,因此源文件中的代码将获得与您在此处复制和粘贴文本时相同的范围。 (从here)无耻地复制

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

  3. 所以,你的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")
    
    })
    
相关问题