Show the code
library(rnaturalearth) # natural earth data
library(ggplot2) # beautiful maps
library(dplyr) # data wrangling
library(sf) # simple (spatial) features
library(cartogram) # cartograms!cartogramA cartogram is a map where the areas of different regions are distorted (increased in size; decreased in size) by the value of some quantitative variable.
library(rnaturalearth) # natural earth data
library(ggplot2) # beautiful maps
library(dplyr) # data wrangling
library(sf) # simple (spatial) features
library(cartogram) # cartograms!options(scipen = 999) # high 'penalty' for scientific notationrnaturalearthmapdata <- ne_countries(scale = "medium", # medium scale
returnclass = "sf") # as sf objectWe make a basic map, reading it into an object called mymap. We then replay mymap.
cartogram requires projected data (Chapter 5), so we need to project the data with st_transform. A number of projections, including the Mercator and Mollweide projections are possibilities. You may need to experiment with a number of projections to see which ones work best in any particular cartogram.
mapdata_proj <- st_transform(mapdata,
3857) # Mercator
# mapdata_proj <- st_transform(mapdata,
# crs = "+proj=moll") # MollweideEach iteration takes a LONG time. Fewer iterations help the time, but each iteration contributes to the distortion, and makes a more cartogram-like cartogram. Because this is the most time intensive step, I time the creation of the cartogram with Sys.time.
start_time <- Sys.time() # time this step
mapdata_cartogram <- cartogram_cont(mapdata_proj,
"pop_est",
itermax = 7)Warning in cartogram_cont.sf(mapdata_proj, "pop_est", itermax = 7): NA not
allowed in weight vector. Features will be removed from Shape.
end_time <- Sys.time()
end_time - start_timeTime difference of 1.750577 mins
fill Colorviridis) Colors