Reputation: 3496
My app has a few charts, and I would like to draw them in a sperate script in order to have a cleaner server.R
which then contains only the bind_shiny
calls.
Also, because I would like to recycle some of the building blocks of my charts, I would like to split the script to draw the charts in smaller parts of code.
Right know, I have a charts.R file like this:
chart1 <- reactive({
cars %>%
ggvis(~speed)
})
chart2 <- reactive({
chart1 %>% layer_bars()
})
The reactivity is not needed of course, but it will in my original application.
Then, I would like to call the chart on server.R this way:
library(shiny)
library(ggvis)
source("charts.R")
shinyServer(function(input, output) {
chart2 %>%
bind_shiny("test1", "test1_ui")
})
ui.R
library(shiny)
library(ggvis)
shinyUI(fluidPage(
fluidRow(titlePanel("My app")),
fluidRow(
column(12,
tags$h1("hello"),
ggvisOutput('test1')
)
)
)
)
I have noticed everything works in charts.R when I put everything in one object, but it does not if I split the function that draws the chart in multiple pieces. However, something like this works
> a <- cars %>%
+ ggvis(~speed)
> a
Guessing layer_histograms()
Guessing width = 0.5 # range / 42
> a %>% layer_bars()
Anybody could explain how to fix the issue and why my two-steps approach works in R but not in Shiny?
Upvotes: 4
Views: 140
Reputation: 4965
If your problem is that you can't see the plot, that is because in your second recative
statement, you need to refer to chart1
as chart1()
. In other words, change your charts.R
to
Charts.R
chart1 <- reactive({
cars %>%
ggvis(~speed)
})
chart2 <- reactive({
chart1() %>% layer_bars()
})
If you want to learn more about reactivity, please check out this link.
Upvotes: 0