user4381526
user4381526

Reputation:

Plotting based on Radio Buttons in R Shiny dashboard

This is my code:

ui <- fluidPage(
  radioButtons("dist", "Distribution type:",
               c("Sepal.Length" = "Length",
                 "Sepal.Width" = "Width",
                 "Petal.Length" = "Length")),
  plotOutput("distPlot")
)

server <- function(input, output) {
  output$distPlot <- renderPlot({
    dist <- switch(input$dist,
                   "Length" = plot(iris$Sepal.Length),
                   "Width" = plot(iris$Sepal.Width),
                   "Length" = plot(iris$Sepal.Length))

    plot(dist)
  })
}

shinyApp(ui, server)
}

What am I doing wrong?

Also, I would like to have a par(mfrow=c(1,2)) plot for each button. How can I do this?

Any help?

Thanks

Upvotes: 1

Views: 1352

Answers (1)

David Jorquera
David Jorquera

Reputation: 2102

You don't need to plot the assigned function, since switchit0s already doing that.

server <- function(input, output) {
  output$distPlot <- renderPlot({
  switch(input$dist,
               "Length" = plot(iris$Sepal.Length),
               "Width" = plot(iris$Sepal.Width),
               "Length" = plot(iris$Sepal.Length))
           })
}

EDIT: Regarding using par (mfrow=c(1,2)) and despite my comment of other alternatives, this is the alternative I came up with:

server <- function(input, output) {
  output$distPlot <- renderPlot({
  par(mfrow=c(1,2))
  switch(input$dist,
               "Length" = plot(iris$Sepal.Length),
               "Width" = plot(iris$Sepal.Width),
               "Length" = plot(iris$Sepal.Length))
  switch(input$dist,
               "Length" = plot(iris$Sepal.Length),
               "Width" = plot(iris$Sepal.Width),
               "Length" = plot(iris$Sepal.Length))
       }) 

Upvotes: 2

Related Questions