5

I'm trying to create a Shiny app where the user can select the x and y axes to plot, then click "Add Graph" for the graph to plot - but this code isn't working and I'm unsure why. Do I need to set input$x_iris and input$y_iris as reactives?

library(shiny)
library(ggplot2)

ui <- fluidPage(

  titlePanel("4 Plot Generator"),

  sidebarLayout(
    sidebarPanel(
      fluidRow(
        column(6, selectInput("x_iris", "X:", choices= c(unique(colnames(iris))))),
        column(6, selectInput("y_iris", "Y:", choices = c(unique(colnames(iris)))))
      ),

      # button to add graph
      # button to remove graph
      fluidRow(
        column(6, actionButton("add_graph", "Add Graph")),
        column(6, actionButton("reset_graph", "Reset Graphs"))
      )

    ),

    # Show graph
    mainPanel(
      plotOutput("plots")
    )
    )
  )

# Define server logic required to draw a histogram
server <- function(input, output) {

  observeEvent(input$add_graph,{
    # not sure why this isn't working
    plot1 <- ggplot(iris, aes(x = input$x_iris, y = input$y_iris)) + geom_point()
    output$plots <- renderPlot({
      plot1
    })
  })

  observeEvent(input$reset_graph,{
    plot1 <- NULL
    output$plots <- renderPlot({
      plot1
    })
  })


}

# Run the application 
shinyApp(ui = ui, server = server)
MayaGans
  • 1,815
  • 9
  • 30

1 Answers1

2

The problem is the selectInput widgets are returning character values and aes() doesn't expect that. So to tell it to evaluate the input values properly, you use the combination of aes_() and as.name():

ggplot(iris, aes_(x = as.name(input$x_iris), y = as.name(input$y_iris)))
Nate
  • 10,361
  • 3
  • 33
  • 40