Search code examples
rshinyr-leaflet

The legend colors are not perfectly similar to color of polygons


I am using the leaflet function to create an interactive map within the shiny framework. Everything looks great except the legend. The colors of the legend are somewhat faded and therefore not perfectly represent the colors of polygons. How can this be solved?

    renderLeaflet ({

    pal8 <- c("#FFFFE5", "#D9F0A3", "#78C679", "#006837") 
  bins=quantile(mapdata_1()$Per), na.color = "#808080",  alpha = FALSE, reverse = F)
   pal <- colorFactor(palette = pal8, domain =NULL, levels=(mapdata_1()$cat), ordered = TRUE, na.color = "#808080",  alpha = FALSE, reverse = F)

     leaflet (mapdata_()) %>% 

                      addProviderTiles("CartoDB.Positron") %>% 
                     clearControls() %>%
                     clearShapes()%>%
                        addPolygons(fillColor = ~pal(cat)) %>% 



                                   addTiles() %>%

      setView(-82.706838, 40.358615, zoom=7) %>%

                        addLegend(position = "bottomright",
                         values = ~cat,

                         pal = pal,
                         title = (paste("%",input$Age_Group_map, input$sex_map, "in", input$Year_map)) ,
                       labFormat = labelFormat(
                      ))

        })

Solution

  • The legend is transparent by default, which affects the appearance of the colours. Change the opacity argument to fix this:

    addLegend(position = "bottomright",
              values = ~cat, 
              pal = pal,
              opacity = 1.0,
              title = (paste("%",input$Age_Group_map, 
                             input$sex_map, "in", input$Year_map)) ,
              labFormat = labelFormat())