绘图不使用Shiny渲染

时间:2018-11-06 04:04:40

标签: r ggplot2 shiny

我正在尝试使用库macheish中的内置数据集创建一个显示ggplot的闪亮应用程序。但是,当我运行代码时,没有出现任何错误,但是我的ggplot不显示。这是我看到的:

No display of ggplot

理想情况下,我想看到类似的东西

With display of ggplot

这是我的代码:

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)

    })
  })
})

有人可以指出我的代码有什么问题吗?

1 个答案:

答案 0 :(得分:1)

这是您需要的更正-

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