闪亮的栅格的反应性表达

时间:2019-11-06 15:35:37

标签: r ggplot2 shiny raster reactive

我正在开发一个简单的闪亮应用程序。 这是我的数据。

  library(data.table)
  library(ggthemes)
  library(ggplot2)
  library(shiny)

  tempList <- list()

  for(i in 1989:1991){

      temp <- as.data.frame(cbind(runif(10,-10.85, 20.02),runif(10, 49.82,59.47)))
      temp$value <- rnorm(10)
      temp$Year <-i
      tempList[[i]] <- temp
  }

  my.df <- rbindlist(tempList)
  names(my.df)[1:2] <- c('lon', 'lat')

我想制作一个闪亮的应用程序,根据用户选择的年份显示每年的栅格数据

  ui <- fluidPage(

          titlePanel('My dat'),
          sliderInput('yearRef','Select Year',min=1989,max=1991,value=1),

          plotOutput(outputId = 'test')
        )


  server <- function(input, output) {

    tempI <- reactive({my.df %>% dplyr::filter(Year == input$yearRef)})

    output$test <- renderPlot({
    ggplot() + geom_raster(data = tempI, aes(x = lon, y = lat, fill = value)) +
    theme_map() + coord_equal() + scale_fill_viridis_c(option = 'C') 
    })
  }

  shinyApp(ui, server)

这给我一个错误,因为tempI是类reactiveExpr,所以tempI不是我理解的数据帧。我该如何纠正?

1 个答案:

答案 0 :(得分:2)

shiny中使用反应性表达式时,必须使用括号。 就您而言:

renderPlot({
    ggplot() + geom_raster(data = tempI(), aes(x = lon, y = lat, fill = value)) +
    theme_map() + coord_equal() + scale_fill_viridis_c(option = 'C') 
    })

您可以将tempI()视为知道其返回值何时过时的函数。一旦发生这种情况(即用户更改滑块后) tempI必须重新评估。因此,它像一个函数一样工作。这也证明了反应性这个名称的合理性。

您可以了解有关反应式表达式here的更多信息。