Search code examples
rshinyggvis

How to embed a ggvis chart from an external source in shiny?


I got already an answer on pretty much the same topic here Dynamic ggvis object in Shiny, but I am still stacked with a similar piece of code and I don't really understand why.

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() 
})

I would like to call chart1 from charts.R into server.R. Everything works with ggvis if I use the commented code in server.R, but it doesn't when I try to call the ggvis function from charts.R (as in the uncommented code).

Also, do you think is a good practice to create multiple .R scripts or shall I go for proper modules?


Solution

  • You need to edit 2 things in your script:

    1. If you want to split the server or ui code into multiple files, you can use source(local=TRUE) to load each file. You can think of this as putting the code in-line, so the code from the sourced files will receive the same scope as if you copied and pasted the text right there. (Shamelessly copied from here)

    2. Reactive objects should be called with parenthesis only in other reactive expressions or render* expressions

    So, your server.R to should look like this:

    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")
    
    })