Global cartogram in R

I am trying to create a global cartogram using the cartogram package in R. I am trying to use the data from wrld_simpl. What I expect is a cartogram in which the Population ("Pop2005" variable) is plotted. The code I have developed is this:

data(wrld_simpl)
world<-wrld_simpl

world_sf = st_as_sf(world)
world_sf_proj = st_transform(world_sf, crs = 3785)

world_cartogram <- cartogram_cont(world_sf_proj, "POP2005")
plot(world_cartogram)

Nonetheless, this has resulted in the following figure: enter image description here

Do you know what is wrong with the code? Maybe the CRS? I have tried to use others CRS but I got the following error: "Error: Using an unprojected map. This function does not give correct centroids and distances for longitude/latitude data: Use "st_transform()" to transform coordinates to another projection."

Upvotes: 2

Views: 400

Answers (1)

Ma&#235;l
Ma&#235;l

Reputation: 52319

Taken from this documentation, it is stated that

The default plot of an sf object is a multi-plot of all attributes, up to a reasonable maximum

If you want to use the base R plot function, then use st_geometry(your_map) to plot (the geometry) an sf object.

Another possibility (which I don't recommend) is to set plot options to 1 plot maximum (options(sf_max.plot=1)), but this plots the first variable, and it might not be the best idea.

library(sf)
library(spData)
library(cartogram)
library(tidyverse)

world_sf = st_as_sf(world)
world_sf_proj = st_transform(world_sf, crs = 3785)
world_cartogram <- cartogram_cont(world_sf_proj, "pop")

plot(st_geometry(world_cartogram))

enter image description here


Now, sf is particularly well suited with ggplot2 and the tidyverse. In that setting, just use ggplot in combination with geom_sf.

ggplot(world_cartogram) +
  geom_sf()

Upvotes: 3

Related Questions