Show Sidebar Hide Sidebar

Lines on Mapbox in R

How to draw a line on Map in R with plotly.

New to Plotly?

Plotly's R library is free and open source!
Get started by downloading the client and reading the primer.
You can set up Plotly to work in online or offline mode.
We also have a quick-reference cheatsheet (new!) to help you get started!

Version Check

Version 4 of Plotly's R package is now available!
Check out this post for more information on breaking changes and new features available in this version.

library(plotly)
packageVersion('plotly')
## [1] '4.9.0.9000'

Mapbox Access Token

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

To draw a line on your map, you either can use Scattermapbox or scattergeo trace type in plotly. This example uses scattermapbox and defines the drawing mode to the combination of markers and line.

Lines on Mapbox maps using Scattermapbox traces

library(plotly)

p <- plot_ly(
  type = 'scattermapbox',
  mode = "markers+lines",
  lon = c(10, 20, 30),
  lat = c(10, 20,30),
  marker = list(size = 10)) %>%
  add_trace(
    type = 'scattermapbox',
    mode = "markers+lines",
    lon = c(-50, -60,40),
    lat = c(30, 10, -20),
    marker = list(size = 10)) %>%
  layout(
    mapbox = list(
      style = "stamen-terrain",
      center = list(lon = 10, lat= 10),
      zoom = 1),
    margin =list(l=0,t=0,b=0,r=0))

# Create a shareable link to your chart
# Set up API credentials: https://plot.ly/r/getting-started
chart_link = api_create(p, filename="line-scattermapbox")
chart_link

Reference

See https://plot.ly/r/reference/#scattermapbox for more information and options!