0
votes

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.

2

2 Answers

0
votes

It would be good to provide a minimally reproducible example, so that we can verify the issue and test the solution. You can try the following:

observeEvent(input$year, {
  if (!is.null(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
      )
  }else{return(NULL)}
})
0
votes

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

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