To introduce the mapview package, make an interactive map with Starbucks coffee shop locations in North Carolina (2012). (Adapted from Machlis.)1

Load Libraries

library(tidyverse)
library(sf)
library(leaflet)
library(mapview)

Load Data

2012 Starbucks locations (data source)

starbucks <- read_csv("data/All_Starbucks_Locations_in_the_US_-_Map.csv")

Subset Data to North Carolina

starbucksNC <- starbucks  %>% 
  filter(State == "NC")

starbucksNC

Transform to Spatial Data

Transform our standard tibble (i.e. the starbucksNC data frame) into a spacial data frame via the simple features function, st_as_sf(). Here we set the map projection to a common standard, WGS84, via the argument crs = 4326.)

sbuxsfc <- st_as_sf(starbucksNC, coords = c("Longitude", "Latitude"),  crs=4326)

Visualize the Map

Below, you can plot the latitude and longitude coordinate, and set the map.types argument to openStreetMap. Base maps are set with map.types. For example a high contrast, black and white basemap can be set with the argument map.types = "Stamen.Toner". See available map types, or leave out the map.types argument for a set of default base maps to choose via the layering button.

#mapview(sbuxsfc, map.types = "Stamen.Toner")
mapview(sbuxsfc)

Save the Map

You can save a map as an interactive HTML page or a static .png, .pdf, or .jpeg file with the mapshot function. For example:

  • mapshot(starNCmap, file = "map.png")
  • mapshot(starNCmap, url = "map.html")

  1. 5 Visualizations in 5 Minutes. ComputerWorld.com by Sharon Machlis

 
R We Having Fun Yet‽ -- Learning Series
Data & Visualization Services
Duke University Libraries
C bn
Shareable via Creative Commons: CC By-NC