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.
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 = shp.data()$stat.selected,
title = "Legend",
opacity = .5)
Where pal
is a quantile color palette as follows
pal <-colorQuantile(c("#B2FF66","#66CC00","#4C9900","#336600","#193300"),
NULL, n = 5, na.color="#FFFFFF")
shp.data()
is a reactive expression that is a shapefile filtered based on user inputs and stat_selected
is the specific statistic that the user selects for mapping onto colors.
I get the following warnings:
Warning in is.na(x) :
is.na() applied to non-(list or vector) of type 'NULL'
Warning in is.na(values) :
is.na() 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 addLegend
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 thestat.selected
variable in double brackets, which seemed to fix the problem:For clarification, the
stat.selected
variable comes from the following switch statement:where
"tot_emp"
,"a_mean"
,"h_mean"
, and"loc_quotient"
are column names in theshp.data
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.