Black Lives Matter. Please consider donating to Black Girls Code today.

# Lines on Mapbox in R

How to draw a line on Map 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.

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

### Lines on Mapbox maps using "Scattermapbox" traces

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.

library(plotly)

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

fig


# Reference

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)
)
)
) 