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.
Diese Übung ist Teil des Kurses
Visualizing Geospatial Data in R
Interaktive Übung
Versuche dich an dieser Übung, indem du diesen Beispielcode vervollständigst.
# Fix the polygon cropping
ggmap(corvallis_map_bw,
base_layer = ggplot(ward_sales, aes(lon, lat))) +
geom_polygon(aes(group = group, fill = ward))