Reputation: 107
I have plotOutput
cyl
in my Shiny app. It relies on observeEvent
and selectizeInput
to display data corresponding to whatever cyl
in mtcars
the user selects.
I am trying to render a plot on start-up, however, that displays data from all cyl
, prior to user selection. In my attempt, I assumed that I could render the initial plot first, and then call observeEvent
. This does not work. What am I doing wrong?
########
### ui
########
ui <- shiny::fluidPage(
shiny::titlePanel("dummy app"),
shiny::sidebarLayout(
shiny::sidebarPanel(
shiny::selectizeInput("cyl", "Cyl",
choices = c("Pick one" = "",
unique(datasets::mtcars$cyl)))
),
shiny::mainPanel(
shiny::plotOutput(outputId = "cyl")
)
)
)
########
### server
########
server <- function(input, output, session) {
### make start-up plot prior to observeEvent
### doesn't do anything
output$cyl <- shiny::renderPlot({
ggplot2::ggplot(datasets::mtcars, ggplot2::aes(x = disp, y = hp)) +
ggplot2::geom_point()
})
### overwrite plot pending selectInput
shiny::observeEvent(input$cyl, {
output$cyl <- shiny::renderPlot({
data <- datasets::mtcars[datasets::mtcars$cyl == input$cyl, ]
ggplot2::ggplot(data, ggplot2::aes(x = disp, y = hp)) +
ggplot2::geom_point()
})
})
}
# Run the application
shinyApp(ui = ui, server = server)
Upvotes: 1
Views: 883
Reputation: 7340
Use this:
########
### ui
########
library(shiny)
ui <- shiny::fluidPage(
shiny::titlePanel("dummy app"),
shiny::sidebarLayout(
shiny::sidebarPanel(
shiny::selectizeInput("cyl", "Cyl",
choices = c("Pick one" = "",
unique(datasets::mtcars$cyl)))
),
shiny::mainPanel(
shiny::plotOutput(outputId = "cyl")
)
)
)
########
### server
########
server <- function(input, output, session) {
### make start-up plot prior to observeEvent
# ### doesn't do anything
mydata <- reactive({
if(input$cyl == "") return(mtcars)
mtcars[mtcars$cyl == input$cyl, ]
})
output$cyl <- shiny::renderPlot({
ggplot2::ggplot(mydata(), ggplot2::aes(x = disp, y = hp)) +
ggplot2::geom_point()
})
}
# Run the application
shinyApp(ui = ui, server = server)
short and clean.
Upvotes: 2