Search code examples
rshinyr-leaflet

leaflet shiny palette issue


The variable I am trying to plot on a leaflet map is binary but I can't manage to have two distinct colors for each value (1 and 0). When the map loads, missing values are plotted in red, but the actual values are of the same color (something in between green and yellow). The 1 values should be green and 0 should be yellow. Here is the content of my server.R:

server <- function(input, output) {

  
  colorpalette1 <- c("#3EA055", "#C68E17")
  
  output$mymap1 <- renderLeaflet({
    leaflet() %>%
      setView(0, 28, 2)
  })
  
  selected <- reactive({
    data2 <- shape_data[[input$year]]
    data2
  })
  
  observeEvent(input$year, {
    bins1 <- c(1, 0)
    pal1 <- colorBin(colorpalette1, domain = selected(), bins = bins1, na.color = "#8C001A")
    
    leafletProxy("mymap1") %>%
      clearShapes() %>%
      addPolygons(data = shape_data,
                  fillColor = ~pal1(selected()),
                  weight = 1,
                  opacity = 1,
                  color = "black",
                  fillOpacity = 0.7
      )
  })
}

input$year is a selectInput that selects the variable to plot on the map.


Solution

  • I found the answer, colorNumeric() was more suitable than colorBin().

    pal1 <- colorNumeric(colorpalette1, domain = shape_data[[input$year]], na.color = "#8C001A")