Arvind Suryanarayana
Arvind Suryanarayana

Reputation: 247

Integrating Shiny with Leaflet

I'm trying to visualise all the trees present in Central Melbourne. The dataset I'm using is available here - Urban Forest Data

I'm successful in plotting all the trees present in the dataset and also colour coded them according to their Life Expectancy.

I was wondering on how I can integrate this with Shiny so that I can filter the plot by the column "Precinct". That is, when I select "CBD", it should plot only trees in that area. My code so far and a screenshot of the working plot is as below:

Code:

library(leaflet)
library(dplyr)
library(readr)
td <- read.csv("treedata.csv", header = TRUE)

pal <- colorNumeric(
  palette = "RdYlGn",
  domain = td$LifeExpectencyValue
)

leaflet(td) %>% addTiles(
  urlTemplate = 'http://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png',
  attribution='Map tiles by <a href="http://stamen.com">Stamen Design</a>, <a href="http://creativecommons.org/licenses/by/3.0">CC BY 3.0</a> &mdash; Map data &copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'
) %>% addCircleMarkers(radius= 5,fillOpacity = 0.5, stroke = FALSE,color=~pal(LifeExpectencyValue),
                                                popup=paste("Name:", td$CommonName, "<br>", "Years Left:", td$LifeExpectency, "<br>", "Genus:", td$Genus)
                       
) %>% addLegend(pal = pal, values = ~LifeExpectencyValue, opacity = 1, title = "Life Expectancy")

Screenshot of the plot: enter image description here

UPDATE:

Shiny Code Tried:

require(rCharts)
library(shiny)

ui <- fluidPage(
  selectInput("precinct",
              label="Precinct",
              choices = sort(td$Precinct),
              selected = "CBD"),
  plotOutput("treedat") #Giving an input name and listing out types to choose in the Shiny app
)

server <- function(input, output){
  
  output$treedat <- renderLeaflet({
    PRECINCT = input$precinct
    precinct = subset(td, precinct == PRECINCT)
    td2 <- leaflet(td) %>% addTiles(
      urlTemplate = 'http://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png',
      attribution='Map tiles by <a href="http://stamen.com">Stamen Design</a>, <a href="http://creativecommons.org/licenses/by/3.0">CC BY 3.0</a> &mdash; Map data &copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'
    ) %>% addCircleMarkers(radius= 5,fillOpacity = 0.5, stroke = FALSE,color=~pal(LifeExpectencyValue),
                           popup=paste("Name:", td$CommonName, "<br>", "Years Left:", td$LifeExpectency, "<br>", "Genus:", td$Genus)
                           
    ) %>% addLegend(pal = pal, values = ~LifeExpectencyValue, opacity = 1, title = "Life Expectency")
    return(td2)
  })
}
shinyApp(ui = ui, server = server)

Getting an error saying object 'Precinct' not found.

Upvotes: 1

Views: 482

Answers (1)

SymbolixAU
SymbolixAU

Reputation: 26258

A couple of points

  1. You are using leaflet in your code, but rCharts in your app. Here I'm just using leaflet in the shiny app. (And, as far as I'm aware rCharts isn't yet on CRAN?)

  2. The choices that populate your drop-down are based on the data. Therefore, I've moved the selectInput into the server using renderUI/UIOutput. I also use as.chacter around the choices so you see the character representation, rather than the factor levels

I've also removed the code that colours the trees as there is no column called LifeExpectancy in the raw data (I'm assuming you've cleand the column headings somewhere?)

And lastly, a couple of small changes to how you subset your data and you're good to go.

library(leaflet)
library(shiny)

ui <- fluidPage(
  uiOutput("precinct"),
  leafletOutput("treedat") #Giving an input name and listing out types to choose in the Shiny app
)

server <- function(input, output){

  # td <- read.csv("~/Desktop/Melbourne_s_Urban_Forest_Tree_data.csv", header = T)

  output$precinct <- renderUI({

    choices <- as.character(unique(td$Precinct))  
    choices <- c('All', choices)
    selectInput(inputId = "precinct", label = "Precinct", choices = choices, selected = "CBD")

  })


  output$treedat <- renderLeaflet({

    ## get the choice from teh drop-down box
    PRECINCT = input$precinct

    ## supbset the data based on the choice
    if(PRECINCT != 'All'){
        td2 <- td[td$Precinct == PRECINCT, ]
    }else{
        td2 <- td
    }
    ## plot the subsetted ata
    td2 <- leaflet(td2) %>% addTiles(
      urlTemplate = 'http://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png',
      attribution='Map tiles by <a href="http://stamen.com">Stamen Design</a>, <a href="http://creativecommons.org/licenses/by/3.0">CC BY 3.0</a> &mdash; Map data &copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>') %>% 
      addCircleMarkers(radius= 5,fillOpacity = 0.5, stroke = FALSE)
    return(td2)
  })
}

shinyApp(ui = ui, server = server)

Upvotes: 2

Related Questions