Black Lives Matter. Please consider donating to Black Girls Code today.
https://www.blackgirlscode.com/

Scattermapbox in R

How to create scattermapbox plots in R with Plotly.


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.

Mapbox Access Token

To plot on Mapbox maps with Plotly you may need a Mapbox account and a public Mapbox Access Token. See our Mapbox Mafig Layers documentation for more information. If you're using a Chart Studio Enterprise server, please see additional instructions here.

Basic Example

library(plotly)

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


dat <- map_data("world", "canada") 
dat <- dat %>% group_by(group)

fig <- plot_mapbox(dat, x = ~long, y = ~lat)
fig <- fig %>% add_paths(size = I(2))
fig <- fig %>% add_segments(x = -100, xend = -50, y = 50, 75)
fig <- fig %>% layout(mapbox = list(zoom = 0,
                       center = list(lat = ~median(lat),
                                     lon = ~median(long))
  ))
fig <- fig %>% config(mapboxAccessToken = Sys.getenv("MAPBOX_TOKEN"))

fig

Multiple Markers

library(plotly)

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

df = read.csv('https://raw.githubusercontent.com/bcdunbar/datasets/master/meteorites_subset.csv')

fig <- df %>% plot_mapbox(lat = ~reclat, lon = ~reclong,
              split = ~class, size=2,
              mode = 'scattermapbox', hoverinfo='name') 
fig <- fig %>% layout(title = 'Meteorites by Class',
         font = list(color='white'),
         plot_bgcolor = '#191A1A', paper_bgcolor = '#191A1A',
         mapbox = list(style = 'dark'),
         legend = list(orientation = 'h',
                       font = list(size = 8)),
         margin = list(l = 25, r = 25,
                       b = 25, t = 25,
                       pad = 2)) 
fig <- fig %>% config(mapboxAccessToken = Sys.getenv("MAPBOX_TOKEN"))

fig

Adding lines to Mapbox

library(plotly)
library(dplyr)

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

# airport locations
air <- read.csv('https://raw.githubusercontent.com/plotly/datasets/master/2011_february_us_airport_traffic.csv')

# flights between airports
flights <- read.csv('https://raw.githubusercontent.com/plotly/datasets/master/2011_february_aa_flight_paths.csv')
flights$id <- seq_len(nrow(flights))

fig <- plot_mapbox(mode = 'scattermapbox') 
fig <- fig %>% add_markers(
    data = air, x = ~long, y = ~lat, text=~airport, color=I("red"),
    size = ~cnt, hoverinfo = "text", alpha = 0.5) 
fig <- fig %>% add_segments(
    data = group_by(flights, id),
    x = ~start_lon, xend = ~end_lon,
    y = ~start_lat, yend = ~end_lat,
    alpha = 0.3, size = I(1), hoverinfo = "none",
    color=I("red")) 
fig <- fig %>% layout(
    plot_bgcolor = '#191A1A', paper_bgcolor = '#191A1A',
    mapbox = list(style = 'dark',
                  zoom = 1.5,
                  center = list(lat = median(air$lat),
                                lon = median(air$long))),
    margin = list(l = 0, r = 0,
                  b = 0, t = 0,
                  pad = 0),
    showlegend=FALSE) 
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)