chokn chokn - 2 months ago 44x
R Question

Leaflet map legend in R Shiny app has doesn't show colors

When I try to add a legend to a leaflet map for a leaflet map (using the Leaflet for R package) incorporated into a Shiny app, the legend does not show the colors of the color palette. Instead it only shows the colors specified for the NA values, in this case, white.

legend without colors

The app does the following:

  • First, it filters a set of data based on user inputs

  • Then it generates a choropleth map from the filtered data

This is the code I used to make the legend:

addLegend(position = "bottomleft",
pal = pal, values =$stat.selected,
title = "Legend",
opacity = .5)

is a quantile color palette as follows

pal <-colorQuantile(c("#B2FF66","#66CC00","#4C9900","#336600","#193300"),
NULL, n = 5, na.color="#FFFFFF")
is a reactive expression that is a shapefile filtered based on user inputs and
is the specific statistic that the user selects for mapping onto colors.

I get the following warnings:

Warning in : applied to non-(list or vector) of type 'NULL'
Warning in : applied to non-(list or vector) of type 'NULL'

I initially tried to make the legend following the example on the leaflet for R page and used the argument
values = ~stat.selected
for the
function, but I got this error:

Error in UseMethod("doResolveFormula") :
no applicable method for 'doResolveFormula' applied to an object of class "NULL"


I was able to make the colors showing up by changing the way I was referencing the values column in the arguments of the AddLegend function. I put the stat.selected variable in double brackets, which seemed to fix the problem:

addLegend(position = "bottomleft",
          pal = pal, values =[[stat.selected]],
          title = "Legend",
          opacity = 1

For clarification, the stat.selected variable comes from the following switch statement:

 stat.selected <- isolate(switch(input$var.stat,
                                "Total employment" = "tot_emp",
                                "Mean annual wage" = "a_mean",
                                "Mean hourly wage" = "h_mean",
                                "Location quotient" = "loc_quotient"

where "tot_emp", "a_mean", "h_mean", and "loc_quotient" are column names in the spatial polygons data frame.

I guess the problem was that I was trying to pass in the column name by variable using a $.

I'm still a fairly novice R user, so if anyone can explain why the example in the Leaflet for R documentation does not work in this case I would appreciate it.