1

I have an actionBotton to randomly pick one column from the first 5 columns from the dataset mtcars and plot it.

Now the actionBotton could do its job but the chart is not plotted at the first place when the app is launched.

Is there any way to have it plotted when the Shiny app is launched.

library(shiny)

server <- function(input, output) {
  X = eventReactive(input$plot,{
    mtcars
  })
  output$plot = renderPlot({
    i = sample(1:5,1)
    plot(X()[,i],ylab=names(mtcars)[i])
  })
}

ui <- fluidPage(
  actionButton("plot","randomly plot"),
  plotOutput("plot")

)

shinyApp(ui = ui, server = server)
John
  • 1,779
  • 3
  • 25
  • 53

1 Answers1

3

You can add the condition is the button hasn't been clicked. Note that button works as a counter so if it hasn't been clicked the value will be 0.

library(shiny)

server <- function(input, output) {
  X = eventReactive(input$plot,{
    mtcars
  })
  output$plot = renderPlot({
    i = sample(1:5,1)
    if(input$plot == 0){
      return(plot(mtcars[,i],ylab=names(mtcars)[i]))
    }
    plot(X()[,i],ylab=names(mtcars)[i])
  })
}

ui <- fluidPage(
  actionButton("plot","randomly plot"),
  plotOutput("plot")

)

shinyApp(ui = ui, server = server)

enter image description here

Pork Chop
  • 28,528
  • 5
  • 63
  • 77