upendra
upendra

Reputation: 2189

ggplot error in R shiny package

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()
  )
})

Upvotes: 2

Views: 544

Answers (1)

Colonel Beauvel
Colonel Beauvel

Reputation: 31161

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.

Upvotes: 3

Related Questions