Janice Luong
Janice Luong

Reputation: 27

Plot not rendering with Shiny

I am trying to create a shiny app that displays a ggplot using a built in data set from the library macheish. However, when I run my code, I do not get any errors, but my ggplot does not display. Here is what I see:

No display of ggplot

Ideally I would like to see something like this

With display of ggplot

Here is my code:

ui.r

library(shiny)
shinyUI(fluidPage(
  sidebarLayout(
    sidebarPanel(
      selectInput(input = "datasets", label = "Choose a Dataset:",
                   choices = c("whately_2015", "orchard_2015"))),
  mainPanel(
    plotOutput("ggPlot"))
    )
  )
)

server.r

library(shiny)
library(ggplot2)
library(macleish)

shinyServer(function(input, output) {

  datasetInput <- reactive({
    switch(input$datasets,
           "whately_2015" = whately_2015,
           "orchard_2015" = orchard_2015)

    output$ggPlot <- renderPlot({
      p <- ggplot(data = input$datasets, aes(y = temperature, x = when)) + 
        geom_line(color = "darkgray") +
        geom_smooth() +
        xlab("Time") +
        ylab("Temperature (in F)") +
        ggtitle("Weather Data in 2015") +
        theme(plot.title = element_text(hjust = 0.5))
      print(p)

    })
  })
})

Could someone help me out by pointing out what is wrong with my code?

Upvotes: 0

Views: 2292

Answers (1)

Shree
Shree

Reputation: 11140

Here's the correction you need -

  datasetInput <- reactive({
    switch(input$datasets,
           "whatley_2015" = whately_2015,
           "orchard_2015" = orchard_2015)
  })

    output$ggPlot <- renderPlot({
      p <- ggplot(data = datasetInput(), aes(y = temperature, x = when)) + 
        geom_line(color = "darkgray") +
        geom_smooth() +
        xlab("Time") +
        ylab("Temperature (in F)") +
        ggtitle("Weather Data in 2015") +
        theme(plot.title = element_text(hjust = 0.5))
      print(p)    
    })

Upvotes: 1

Related Questions