Powered by AppSignal & Oban Pro

Map data: map_data

notebooks/map_data.livemd

Map data: map_data

Mix.install([
  {:giggly, path: Path.join(__DIR__, "..")},
  {:kino, "~> 0.19"}
  ])

About this notebook

This notebook follows the examples on ggplot2's reference page for map_data(), in the order the page gives them. Each example shows ggplot2's code first and then Giggly's. An example Giggly cannot draw yet keeps its ggplot2 code and names what it is waiting for, so the page is also a list of what remains.

map_data() turns a map from the maps package, such as the US states, the US counties or the world, into a data frame that ggplot2 can plot, one row per point of the map's outlines. Not in Giggly yet: map data from the maps package.

A choropleth of US states

The example joins each state's outline to R's USArrests table by the state's name, puts the rows back in drawing order, and fills each state by its rate of arrests for assault, in an Albers projection.

if (require("maps")) {
states <- map_data("state")
arrests <- USArrests
names(arrests) <- tolower(names(arrests))
arrests$region <- tolower(rownames(USArrests))

choro <- merge(states, arrests, sort = FALSE, by = "region")
choro <- choro[order(choro$order), ]
ggplot(choro, aes(long, lat)) +
  geom_polygon(aes(group = group, fill = assault)) +
  coord_map("albers",  lat0 = 45.5, lat1 = 29.5)
}

Not in Giggly yet: map data from the maps package, the USArrests dataset, geom_polygon(), and coord_map().

Filling by a ratio

if (require("maps")) {
ggplot(choro, aes(long, lat)) +
  geom_polygon(aes(group = group, fill = assault / murder)) +
  coord_map("albers",  lat0 = 45.5, lat1 = 29.5)
}

Not in Giggly yet: map data from the maps package, the USArrests dataset, geom_polygon(), and coord_map().