2.2 Maps

2.2.1 Using scatter traces

As shown in polygons, it is possible to create maps using plotly’s default (Cartesian) coordinate system, but plotly.js also has support for plotting scatter traces on top of either a custom geo layout or a mapbox layout. Figure 2.20 compares the three different layout options in a single subplot.

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

map1 <- plot_ly(dat, x = ~long, y = ~lat) %>% 
  add_paths(size = I(1)) %>%
  add_segments(x = -100, xend = -50, y = 50, 75)

map2 <- plot_mapbox(dat, x = ~long, y = ~lat) %>% 
  add_paths(size = I(2)) %>%
  add_segments(x = -100, xend = -50, y = 50, 75) %>%
  layout(mapbox = list(zoom = 0,
      center = list(lat = ~median(lat), lon = ~median(long))
   ))

# geo() is the only object type which supports different map projections
map3 <- plot_geo(dat, x = ~long, y = ~lat) %>% 
  add_markers(size = I(1)) %>%
  add_segments(x = -100, xend = -50, y = 50, 75) %>%
  layout(geo = list(projection = list(type = "mercator")))

subplot(map1, map2) %>%
  subplot(map3, nrows = 2) %>% 
  hide_legend()