library(data.table)
library(ggplot2)
library(kableExtra)
library(RColorBrewer)
library(magrittr)
library(devtools)
library(sf)
library(spData)
Demos for deandevl/RspatialPkg
Load the required R Packages from CRAN:
Load the package deandevl/RspatialPkg
from github:
::install_github('deandevl/RspatialPkg') devtools
The first demo uses the get_geom_sf function to create a choropleth map of population densities across world continents.
The raw data originates from the spData package with a simple feature object(sf) containing country population numbers, areas, and boundary geometries across the world.
name_long | continent | area_km2 | pop | geom |
---|---|---|---|---|
Fiji | Oceania | 19289.97 | 885806 | MULTIPOLYGON (((-180 -16.55... |
Tanzania | Africa | 932745.79 | 52234869 | MULTIPOLYGON (((33.90371 -0... |
Western Sahara | Africa | 96270.60 | NA | MULTIPOLYGON (((-8.66559 27... |
Canada | North America | 10036042.98 | 35535348 | MULTIPOLYGON (((-132.71 54.... |
United States | North America | 9510743.74 | 318622525 | MULTIPOLYGON (((-171.7317 6... |
Kazakhstan | Asia | 2729810.51 | 17288285 | MULTIPOLYGON (((87.35997 49... |
Uzbekistan | Asia | 461410.26 | 30757700 | MULTIPOLYGON (((55.96819 41... |
Papua New Guinea | Oceania | 464520.07 | 7755785 | MULTIPOLYGON (((141.0002 -2... |
Using data.table techniques we will group the “pop” and “area_km2” variables by the “continent” variable along with a union of the “geom” polygons variable:
<- data.table::as.data.table(spData::world) %>%
world_agg_sf
.[, Pop = sum(pop, na.rm = TRUE),
.(Area = sum(area_km2),
N = .N,
Density = round(sum(pop, na.rm = T)/sum(area_km2)),
geometry = sf::st_union(geom)), by = continent] %>%
order(-N)] %>%
.[1:6,] %>%
.[::st_as_sf(.) sf
continent | Pop | Area | N | Density | geometry |
---|---|---|---|---|---|
Africa | 1154946633 | 29946198 | 51 | 39 | MULTIPOLYGON (((36.86623 22... |
Asia | 4311408059 | 31252459 | 47 | 138 | MULTIPOLYGON (((36.14976 35... |
Europe | 669036256 | 23065219 | 39 | 29 | MULTIPOLYGON (((26.29 35.29... |
North America | 565028684 | 24484309 | 18 | 23 | MULTIPOLYGON (((-82.26815 2... |
South America | 412060811 | 17762592 | 13 | 23 | MULTIPOLYGON (((-66.95992 -... |
Oceania | 37757833 | 8504489 | 7 | 4 | MULTIPOLYGON (((166.7932 -1... |
Create a choropleth map based on the “Density” variable for the “continent” using RspatialPkg::get_geom_sf. Add a mapping that labels the continents.
<- RspatialPkg::get_geom_sf(
world_agg_plot sf = world_agg_sf,
aes_fill = "Density",
panel_color = "green",
hide_x_tics = T,
hide_y_tics = T,
scale_breaks = seq(0,150,25),
scale_labels = seq(0,150,25),
scale_colors = RColorBrewer::brewer.pal(n = 9, name = "YlOrRd"),
legend_key_width = 0.7,
legend_key_height = 1.0
+
) ::get_geom_sf(
RspatialPkgsf = world_agg_sf,
aes_text = "continent",
text_color = "red",
adding = T
) world_agg_plot