2

I have just learning R shiny package and for one of the exercise in a course, we have to create an app that has two dropdown menus in the sidebar and a ggplot2 plot in the main panel

I almost figured out most of the R code but i am getting error (object 'input' not found) during plotting. Can someone point to me of where i am doing wrong?

ui.R

library(shiny)

shinyUI(fluidPage(

  # Application title
  titlePanel("Demonstration of 2 dropdown menus"),

  # Sidebar with a slider input for number of bins
  sidebarLayout(
    sidebarPanel(
      selectInput("element_id1", "select variable for x-axis", c("mpg", "cyl", "disp", "hp", "wt"), selected = "wt"),
      selectInput("element_id2", "select variable for x-axis", c("mpg", "cyl", "disp", "hp", "wt"), selected = "mpg")
    ),

    # Show a plot of the generated distribution
    mainPanel(
      textOutput("id1"),
      textOutput("id2"),
      plotOutput("plt")
    )
  )
))

server.R

library(shiny)
library(ggplot2)

shinyServer(function(input, output) {
  output$id1 <- renderText({
    sprintf("You have selected %s on the x-axis", input$element_id1)
})
  output$id2 <- renderText({
    sprintf("You have selected %s on the y-axis", input$element_id2)
  })
  output$plt <- renderPlot(
    ggplot(mtcars, aes(x = input$element_id1, y = input$element_id2)) + geom_point()
  )
})
2
  • 1
    Have you tried: ggplot(mtcars, aes_string(x = input$element_id1, y = input$element_id2)) ? Commented Sep 7, 2015 at 10:55
  • No, but i have now and it worked. How is this different than aes? Thanks anyway for your help Commented Sep 7, 2015 at 10:58

1 Answer 1

3

You are providing character variable to mention which are your axis in ggplot. Hence you need to use aes_string when you build your graph:

ggplot(mtcars, aes_string(x = input$element_id1, y = input$element_id2)) + geom_point()

Dummy example:

df = data.frame(x=1:3, y=c(4,5.6,1))

ggplot(df, aes(x=x, y=y)) + geom_line()
ggplot(df, aes_string(x='x', y='y')) + geom_line()

Both provide the same results.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.