Choropleth map
Now that you understand drawing polygons, let's get your polygons on a map. Remember, you replace your ggplot()
call with a ggmap()
call and the original ggplot()
call moves to the base_layer()
argument, then you add your polygon layer as usual:
ggmap(corvallis_map_bw,
base_layer = ggplot(ward_sales,
aes(lon, lat))) +
geom_polygon(aes(group = group, fill = ward))
Try it out in the console now!
Uh oh, things don't look right. Wards 1, 3 and 8 look jaggardy and wrong. What's happened? Part of the ward boundaries are beyond the map boundary. Due to the default settings in ggmap()
, any data off the map is dropped before plotting, so some polygon boundaries are dropped and when the remaining points are joined up you get the wrong shapes.
Don't worry, there is a solution: ggmap()
provides some arguments to control this behaviour. Arguments extent = "normal"
along with maprange = FALSE
force the plot to use the data range rather than the map range to define the plotting boundaries.
This exercise is part of the course
Visualizing Geospatial Data in R
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Fix the polygon cropping
ggmap(corvallis_map_bw,
base_layer = ggplot(ward_sales, aes(lon, lat))) +
geom_polygon(aes(group = group, fill = ward))