Is there a way to use leaflet and addCircles with categorical variables?


#1

Hi everyone,

My question is:

Is there a way to use leaflet and addCircles with categorical variables?
In the example below is easy to see how the icons are highlighted based on a continuous variable (magnitude). Is it possible to run this for lets say: "hillary voters" "trump voters" and "did not vote"?

Thanks for your help

      library(shiny)
      library(leaflet)
      library(RColorBrewer)

  ui <- bootstrapPage(
  tags$style(type = "text/css", "html, body {width:100%;height:100%}"),
  leafletOutput("map", width = "100%", height = "100%"),
  absolutePanel(top = 10, right = 10,
   sliderInput("range", "Magnitudes", min(quakes$mag), max(quakes$mag),
   value = range(quakes$mag), step = 0.1
  ),
    selectInput("colors", "Color Scheme",
    rownames(subset(brewer.pal.info, category %in% c("seq", "div")))
  ),
  checkboxInput("legend", "Show legend", TRUE)
  )
  )

 server <- function(input, output, session) {

 # Reactive expression for the data subsetted to what the user selected
   filteredData <- reactive({
    quakes[quakes$mag >= input$range[1] & quakes$mag <= input$range[2],]
     })

    # This reactive expression represents the palette function,
    # which changes as the user makes selections in UI.
   colorpal <- reactive({
    colorNumeric(input$colors, quakes$mag)
    })

    output$map <- renderLeaflet({
    # Use leaflet() here, and only include aspects of the map that
     # won't need to change dynamically (at least, not unless the
    # entire map is being torn down and recreated).
   leaflet(quakes) %>% addTiles() %>%
    fitBounds(~min(long), ~min(lat), ~max(long), ~max(lat))
    })


    observe({
     pal <- colorpal()

     leafletProxy("map", data = filteredData()) %>%
      clearShapes() %>%
        addCircles(radius = ~10^mag/10, weight = 1, color = "#777777",
          fillColor = ~pal(mag), fillOpacity = 0.7, popup = ~paste(mag)
         )
         })

       # Use a separate observer to recreate the legend as needed.
    observe({
      proxy <- leafletProxy("map", data = quakes)


       proxy %>% clearControls()
       if (input$legend) {
       pal <- colorpal()
       proxy %>% addLegend(position = "bottomright",
      pal = pal, values = ~mag
      )
      }
     })
     }

      shinyApp(ui, server)

#2

Yes; instead of colorNumeric, see colorFactor.