Hello everyone,
I'm new to shiny and recently started learning about modules. After playing around for a good time, I still struggle to understand what I can return from a moduleServer().
Problem
I created a small shiny module setup, where a slider changes the plot limits. In Case 1, the ggplot() is rendered inside the module and returned afterward. In Case 2, the ggplot() gets returned and rendered afterward. I would expect both setups to work the same, yet Case 1 does work while Case 2 does not.
Questions
Question 1: Where is the mistake?
Question 2: What would a working Case 2 look like, where a server module returns a ggplot()?
Thanks in advance,
Simon
Setup
library(tidyverse)
library(shiny)
x <- 1:100
y <- rnorm(x)
my_data <- data.frame(x, y)
my_plot <- ggplot(my_data, aes(x, y)) + geom_point()
my_plot
sliderUI <- function (id) {
ns <- NS(id)
fluidRow(sliderInput(inputId = ns("slider"), label = NULL, min = 1, max = 100, value = c(1, 100)))
}
ui <- fluidPage(
sliderUI("my_slider_plot"),
plotOutput("plot")
)
Case 1: works
# reactive(ggplot()) -> renderPlot() -> return()
sliderServer <- function (id, plot) {
moduleServer(
id,
module = function (input, output, session) {
sliderReactive <- reactive({
plot + xlim(c(input$slider[1], input$slider[2]))
})
return(renderPlot(sliderReactive()))
}
)
}
server <- function (input, output) {
output$plot <- sliderServer("my_slider_plot", plot = my_plot)
}
shinyApp(ui, server)
Case 2: does not work
# reactive(ggplot()) -> return() -> renderPlot()
sliderServer <- function (id, plot) {
moduleServer(
id,
module = function (input, output, session) {
sliderReactive <- reactive({
plot + xlim(c(input$slider[1], input$slider[2]))
})
return(sliderReactive())
}
)
}
server <- function (input, output) {
output$plot <- renderPlot(sliderServer("my_slider_plot", plot = my_plot))
}
shinyApp(ui, server)