Get Started

addPolygon() Options

So far we have used the default appearance for addPolygons(). There are several more ways to customize the polygons.

The arguments to addPolygons() we will focus on are:

  • weight: the thickness of the boundary lines in pixels
  • color: the color of the polygons
  • label: the information to appear on hover
  • highlightOptions: options to highlight a polygon on hover
addPolygons(weight = 2,
           color = "red",
           label = ~paste0("Total Income: ", dollar(income)),
           highlight = highlightOptions(weight = 10,
                                       color = "blue",
                                       bringToFront = TRUE))

The high_inc SpatialPolygonsDataFrame you created in the previous exercise has been loaded for you.

This is a part of the course

“Interactive Maps with leaflet in R”

View Course

Exercise instructions

  • Use the arguments of addPolygons() to map the high income zip codes in NC with:
    • A boundary thickness of 1 pixel,
    • Polygons that are colored with the nc_pal palette and are highlighted on hover, and
    • Labels that display the words "Mean Income:" followed by the mean income of the zip code.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# create color palette with colorNumeric()
nc_pal <- colorNumeric("YlGn", domain = high_inc@data$mean_income)

high_inc %>%
  leaflet() %>%
  addTiles() %>%
  # set boundary thickness to 1 and color polygons
  addPolygons(___ = ___, ___ = ~nc_pal(mean_income),
              # add labels that display mean income
              label = ___("Mean Income: ", dollar(mean_income)),
              # highlight polygons on hover
              ___ = highlightOptions(weight = 5, color = "white",
              bringToFront = TRUE))
Edit and Run Code