Mapbox Layers in R

How to make Mapbox maps in R with various base layers, with or without needing a Mapbox Access token.


New to Plotly?

Plotly is a free and open-source graphing library for R. We recommend you read our Getting Started guide for the latest installation or upgrade instructions, then move on to our Plotly Fundamentals tutorials or dive straight in to some Basic Charts tutorials.

How Layers Work in Mapbox Maps

If your figure contains one or more traces of type scattermapbox, choroplethmapbox or densitymapbox, the layout of your figure contains configuration information for the map itself.

The map is composed of layers of three different types.

  1. layout.mapbox.style defines the lowest layers, also known as your "base map"
  2. the various traces in the plot_ly call signature are by default rendered above the base map (this can be controlled via the use of below attribute).
  3. the layout.mapbox.layers attribute accepts an array that defines layers that are by default rendered above the traces in the plot_ly call signature (this can be controlled via the below attribute).

Mapbox Access Tokens and When You Need Them

The word "mapbox" in trace names and the layout.mapbox attribute refers to the Mapbox GL JS open-source library. If the basemap you define using layout.mapbox.style uses data from the Mapbox service that requires API authentication, then you will need to register for a free account at https://mapbox.com/ and obtain a Mapbox Access token.

If you're using a Chart Studio Enterprise server, please see additional instructions here.

The following values of layout.mapbox.style DO require an Access Token:

  1. basic, streets, outdoors, light, dark, satellite, or satellite-streets yeild maps composed of vector tiles from the Mapbox service, and do require a Mapbox Access Token or an on-premise Mapbox installation.
  2. A Mapbox service style URL, which requires a Mapbox Access Token or an on-premise Mapbox installation.
  3. A Mapbox Style object as defined at mapbox docs

We recommend setting your MapBox Access Token as an environment variable in your R environment. That way, your token will not be committed to version control. See Basemap Requiring MapBox Access Token

The following values of layout.mapbox.style DO NOT require an Access Token:

  1. white-bg yields an empty white canvas which results in no external HTTP requests
  2. open-street-map, carto-positron, carto-darkmatter, stamen-terrain, stamen-toner or stamen-watercolor yeild maps composed of raster tiles from various public tile servers which do not require signups or access tokens

Using layout.mapbox.layers to Specify a Base Map

If you have access to your own private tile servers, or wish to use a tile server not included in the list above, the recommended approach is to first set layout.mapbox.style to "white-bg" and then set layout.mapbox.layers to below to specify a custom base map.

If you omit setting layout.mapbox.layers to below, when using this approach, your data will likely be hidden by fully-opaque raster tiles!

OpenStreetMap Tiles, no Token Needed

This chart demonstrates how to use "open-street-map" tiles as the base map for a chart. A Mapbox Access Token is not required.

library(plotly)

us_cities = read.csv("https://raw.githubusercontent.com/plotly/datasets/master/us-cities-top-1k.csv")

fig <- us_cities 
fig <- fig %>%
  plot_ly(
    lat = ~lat,
    lon = ~lon,
    marker = list(color = "fuchsia"),
    type = 'scattermapbox',
    hovertext = us_cities[,"City"]) 
fig <- fig %>%
  layout(
    mapbox = list(
      style = 'open-street-map',
      zoom =2.5,
      center = list(lon = -88, lat = 34))) 

fig

Base Map Below A Trace: No Token Needed

This chart demonstrates how to use a public USGS imagery map as a base map using layout.mapbox.layers. The map is rendered below the trace.

library(plotly)

us_cities = read.csv("https://raw.githubusercontent.com/plotly/datasets/master/us-cities-top-1k.csv")

fig <- us_cities 
fig <- fig %>%
  plot_ly(
    lat = ~lat,
    lon = ~lon,
    type = "scattermapbox",
    hovertext = us_cities[,"City"],
    marker = list(color = "fuchsia")) 
fig <- fig %>%
  layout(mapbox= list(
    style = "white-bg",
    zoom = 3,
    center = list(lon = -93 ,lat= 41),
    layers = list(list(
      below = 'traces',
      sourcetype = "raster",
      source = list("https://basemap.nationalmap.gov/arcgis/rest/services/USGSImageryOnly/MapServer/tile/{z}/{y}/{x}")))))

fig

Maps Below and Above A Trace: No Token Needed

This example uses the same base map below the trace as the one above.

In addition, a WMS layer map from Environment Canada (which displays near-real-time radar imagery in partly-transparent raster tiles) is rendered above the scattermapbox trace, as is the default:

library(plotly)
fig <- us_cities 
fig <- fig %>%
  plot_ly(
    lat = ~lat,
    lon = ~lon,
    type = "scattermapbox",
    hovertext = us_cities[,"City"],
    marker = list(color = "fuchsia")) 
fig <- fig %>%
  layout(
    mapbox= list(
      style = "white-bg",
      sourcetype = 'raster',
      zoom = 3,
      center = list(lon = -93 ,lat= 41),
      layers = list(list(
        below = 'traces',
        sourcetype = "raster",
        source = list("https://basemap.nationalmap.gov/arcgis/rest/services/USGSImageryOnly/MapServer/tile/{z}/{y}/{x}")),
        list(
          sourcetype = "raster",
          source = list("https://geo.weather.gc.ca/geomet/?SERVICE=WMS&VERSION=1.3.0&REQUEST=GetMap&BBOX={bbox-epsg-3857}&CRS=EPSG:3857&WIDTH=1000&HEIGHT=1000&LAYERS=RADAR_1KM_RDBR&TILED=true&FORMAT=image/png")))))

fig

Map Requiring MapBox Access Token

This example demonstrates how to use a MapBox Access token in order to use a "dark" base map from MapBox, which requires API authentication.

In this case, the Access Token is stored in an environment variable which is then passed to the chart configuration call signature.

library(plotly)

mapboxToken <- paste(readLines("../.mapbox_token"), collapse="")    # You need your own token
Sys.setenv("MAPBOX_TOKEN" = mapboxToken) # for Orca

us_cities = read.csv("https://raw.githubusercontent.com/plotly/datasets/master/us-cities-top-1k.csv")

fig <- us_cities 
fig <- fig %>%
  plot_ly(
    lat = ~lat,
    lon = ~lon,
    marker = list(color = "fuchsia"),
    type = 'scattermapbox',
    hovertext = us_cities[,"City"]) 
fig <- fig %>%
  layout(
    mapbox = list(
      style = 'dark',
      zoom =2.5,
      center = list(lon = -88, lat = 34))) 
fig <- fig %>%
  config(mapboxAccessToken = Sys.getenv("MAPBOX_TOKEN"))

fig

Reference

See https://plotly.com/r/reference/#scattermapbox for more information and options!

What About Dash?

Dash for R is an open-source framework for building analytical applications, with no Javascript required, and it is tightly integrated with the Plotly graphing library.

Learn about how to install Dash for R at https://dashr.plot.ly/installation.

Everywhere in this page that you see fig, you can display the same figure in a Dash for R application by passing it to the figure argument of the Graph component from the built-in dashCoreComponents package like this:

library(plotly)

fig <- plot_ly() 
# fig <- fig %>% add_trace( ... )
# fig <- fig %>% layout( ... ) 

library(dash)
library(dashCoreComponents)
library(dashHtmlComponents)

app <- Dash$new()
app$layout(
    htmlDiv(
        list(
            dccGraph(figure=fig) 
        )
     )
)

app$run_server(debug=TRUE, dev_tools_hot_reload=FALSE)