Search code examples
rshinydashboard

R Shiny dashboard - how to interactively select x and y axis for a scatter plot using Select box?


I want to build an interactive scatter plot where x and y axes can be selected using select box on the basis of columns in a dataframe.

Here is the example using mtcars - I use colnames(mtcars) to obtain values for the two select-boxes. But I get the following error: "Error in .subset2(x, "impl")$defineOutput: Unexpected gg output for scatterUnexpected ggplot output for scatter"

What am I doing wrong? Is there something wrong with colnames(mtcars)?

library(shiny)
library(shinydashboard)
library(ggplot2)


ui <- dashboardPage(
  dashboardHeader(),
  dashboardSidebar(),
  dashboardBody(
    fluidRow(
      box(selectInput("scat_x", label = h2("select x-axis"), 
                      choices = colnames(mtcars)),
          selectInput("scat_y", label = h2("select y-axis"), 
                      choices = colnames(mtcars))),
      box(plotOutput("scatter", height = 250))
    )
    
  )
)

server <- function(input, output) {
  output$scatter<- ggplot(mtcars, aes(x=input$scat_x, y=input$scat_y)) + 
    geom_point()
}
  

shinyApp(ui, server)

Solution

    1. To output ggplot, you need to wrap your ggplot object in renderPlot({})
    2. You need to use aes_string because you are passing column names as strings into ggplot.
    library(shiny)
    library(shinydashboard)
    library(ggplot2)
    
    
    ui <- dashboardPage(
        dashboardHeader(),
        dashboardSidebar(),
        dashboardBody(
            fluidRow(
                box(selectInput("scat_x", label = h2("select x-axis"), 
                                choices = colnames(mtcars)),
                    selectInput("scat_y", label = h2("select y-axis"), 
                                choices = colnames(mtcars))),
                box(plotOutput("scatter", height = 250))
            )
            
        )
    )
    
    server <- function(input, output) {
        output$scatter<- renderPlot({
            ggplot(mtcars, aes_string(x=input$scat_x, y=input$scat_y)) + geom_point()
        })
    }
    
    
    shinyApp(ui, server)