Warm tip: This article is reproduced from stackoverflow.com, please click
leaflet r shiny

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

发布于 2020-04-20 10:55:43

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 = 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"
Questioner
chokn
Viewed
46
chokn 2015-06-05 22:57

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 = shp.data()[[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 shp.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.