Skip to content

NA value not positioned correctly in legend for continuous variables #615

@Harrison8

Description

@Harrison8

Issue: In legends for continuous variables, the NA value is out of line with the rest of the color scale. It is positioned to the right, causing the legend box to be very wide.

Workaround: Add CSS to the leaflet map using this code from the htmlwidgets package:

css_fix <- "div.info.legend.leaflet-control br {clear: both;}" # CSS to correct spacing
html_fix <- htmltools::tags$style(type = "text/css", css_fix)  # Convert CSS to HTML
m %<>% htmlwidgets::prependContent(html_fix)                   # Insert into leaflet HTML code

Explanation of issue and workaround: The NA value used to fall below and in line with the rest of the color scale, with a line break between the color scale and the NA value. The line break requires an HTML tag <br clear:"both"> to position it correctly in line with the rest of the color scale. The HTML tag has been removed from Leaflet, allowing the NA value to float to the right. (Leaflets produced in August of 2017 did not have this issue. Also, for discrete variables, there is no line break, and the NA value is correctly positioned in line with the other legend entries.)

Currently, the legend HTML is formatted like this:

<div class="info legend leaflet-control">     # Opens the legend section
  <div style="margin-bottom:3px">...</div>    # Legend title
  <div style="float: left;">...</div>         # Color scale
  <div style="float: left;">...</div>         # Corresponding number scale
  <br>                                        # Line break
  <div>...</div>                              # NA color and the text "NA"

It results in the NA value moving to the right of the other legend entries, rather than below them:
image

The line break used to have an HTML tag <br clear:"both"> that resulted in the NA value falling in the correct place:
image

I don't think this issue is related to the R code that I've used, but here it is. map is a SpatialPolygonsDataFrame.

pal <- colorNumeric(
      palette = brewer.pal(9, "BuPu"),
      domain = map@data$var)

m <- leaflet(map) %>%
  addTiles() %>%
  addPolygons(fillColor = ~pal(var)) %>%
  addLegend(
    pal = pal, 
    values = ~var, 
    title = "Bachelor's Degree<br>or Higher",
    position = "bottomright")

saveWidget(m, "output.html")

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions