简体   繁体   中英

reactive expression for raster in shiny

I am working on a simple shiny app. Here is my data.

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

I want to make a shiny app that displays the raster for each year based on which year the users select

  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)

It gives me an error that tempI is not a dataframe which I understand is causing since tempI is class reactiveExpr . How do I correct it?

when working with reactive expressions in shiny you have to use paranthesis. In your case:

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

You can think of tempI() as a function that knows when its return-value is outdated. As soon as this happens (ie as soon as the user changes the slider) tempI has to be reevaluated. Hence it works like a function. This also justifies the name reactive.

You can learn more about reactive expressions here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM