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