Rental Listings Part 3 - Mapping with Leaflet

Mar 28, 2017 · 1693 words · 8 minutes read R

Leaflet is an awesome package for creating interactive maps in R. It’s a wrapper around the open-source leafletjs library, so it’s also easy to embed the maps into web pages.

Listing Price

First thing to do is create a color palette. Leaflet has a few color* functions for mapping data values to colors from a color palette. I used the viridis color palette because it’s the best to construct deciles.

pal <- colorQuantile(palette = viridis_pal(option = "D")(10),
                     domain = log(tidy$price),
                     n = 10)

Mapping with Leaflet is familiar to anyone who’s used ggplot2 – pass the data to leaflet which initializes the map widget, add map tiles (e.g. addProviderTiles), then add markers, a legend, and mini map. In this case, I wanted to see the individual listings colorized by the log of the listing price.

tidy %>%
    leaflet() %>%
        addProviderTiles("CartoDB.Positron") %>%
        addCircles(
            lng = ~longitude,
            lat = ~latitude,
            color = ~pal(log(price)),
            radius = 100,
            stroke = FALSE,
            opacity = 0.5,
            highlightOptions = highlightOptions(
                fillOpacity = 1,
                bringToFront = TRUE)) %>%
        setView(
            lng = nyc_center$lon,
            lat = nyc_center$lat,
            zoom = 11) %>%
        addLegend(
            position = "bottomleft",
            pal = pal,
            values = ~log(price),
            title = "log(Price) Decile",
            opacity = 1) %>%
       addMiniMap(
           position = "bottomright",
           toggleDisplay = TRUE)