R Language Introduction to Geographical Maps Interactive plotly maps


The plotly package allows many kind of interactive plots, including maps. There are a few ways to create a map in plotly. Either supply the map data yourself (via plot_ly() or ggplotly()), use plotly's "native" mapping capabilities (via plot_geo() or plot_mapbox()), or even a combination of both. An example of supplying the map yourself would be:

map_data("county") %>%
    group_by(group) %>%
    plot_ly(x = ~long, y = ~lat) %>%
    add_polygons() %>%
        xaxis = list(title = "", showgrid = FALSE, showticklabels = FALSE),
        yaxis = list(title = "", showgrid = FALSE, showticklabels = FALSE)

enter image description here

For a combination of both approaches, swap plot_ly() for plot_geo() or plot_mapbox() in the above example. See the plotly book for more examples.

The next example is a "strictly native" approach that leverages the layout.geo attribute to set the aesthetics and zoom level of the map. It also uses the database world.cities from maps to filter the Brazilian cities and plot them on top of the "native" map.

The main variables: pophis a text with the city and its population (which is shown upon mouse hover); qis a ordered factor from the population's quantile. ge has information for the layout of the maps. See the package documentation for more information.

dfb <- world.cities[world.cities$country.etc=="Brazil",]
dfb$poph <- paste(dfb$name, "Pop", round(dfb$pop/1e6,2), " millions")
dfb$q <- with(dfb, cut(pop, quantile(pop), include.lowest = T))
levels(dfb$q) <- paste(c("1st", "2nd", "3rd", "4th"), "Quantile")
dfb$q <- as.ordered(dfb$q)

ge <- list(
  scope = 'south america',
  showland = TRUE,
  landcolor = toRGB("gray85"),
  subunitwidth = 1,
  countrywidth = 1,
  subunitcolor = toRGB("white"),
  countrycolor = toRGB("white")

plot_geo(dfb, lon = ~long, lat = ~lat, text = ~poph,
    marker = ~list(size = sqrt(pop/10000) + 1, line = list(width = 0)),
    color = ~q, locationmode = 'country names') %>%
layout(geo = ge, title = 'Populations<br>(Click legend to toggle)')

This is a snapshot