rgeospatialcartogram

Use "st_transform()" to transform coordinates to another projection - when creating cartogram


I have a shapefile of population estimates of different administrative levels on Nigeria and I want to create a cartogram out of it.

I used the cartogram package and tried the following

library(cartogram)
admin_lvl2_cartogram <- cartogram(admin_level2_shape, "mean", itermax=5)

However this gives me an error stating "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." I'm not sure how to resolve this

To recreate the initial data

Download the data using the wopr package

library(wopr)
catalogue <- getCatalogue()
# Select files from the catalogue by subsetting the data frame
selection <- subset(catalogue,
                    country == 'NGA' &
                      category == 'Population' & 
                      version == 'v1.2')
# Download selected files
downloadData(selection)

Manually unzip the downloaded zip file (NGA_population_v1_2_admin.zip) and read in the data

library(rgdal)
library(here)

admin_level2_shape <- readOGR(here::here("wopr/NGA/population/v1.2/NGA_population_v1_2_admin/NGA_population_v1_2_admin_level2_boundaries.shp"))

Solution

  • The function spTransform in the sp package is probably easiest because the readOGR call returns a spatial polygon defined in that package.

    Here's a full example that transforms to a suitable projection for Nigeria, "+init=epsg:26331". You'll probably have to Google to find the exact one for your needs.

    #devtools::install_github('wpgp/wopr')
    library(wopr)
    library(cartogram)
    library(rgdal)
    library(sp)
    library(here)
    
    catalogue <- getCatalogue()
    # Select files from the catalogue by subsetting the data frame
    selection <- subset(catalogue, country == 'NGA' & category == 'Population' & version == 'v1.2')
    # Download selected files
    downloadData(selection)
    unzip(here::here("wopr/NGA/population/v1.2/NGA_population_v1_2_admin.zip"), 
        overwrite = T, 
        exdir = here::here("wopr/NGA/population/v1.2"))
    admin_level2_shape <- readOGR(here::here("wopr/NGA/population/v1.2/NGA_population_v1_2_admin/NGA_population_v1_2_admin_level2_boundaries.shp"))
    
    transformed <- spTransform(admin_level2_shape, CRS("+init=epsg:26331"))
    admin_lvl2_cartogram <- cartogram(transformed, "mean", itermax=5)
    

    I confess I don't know anything about the specific packages so I don't know if what is produced is correct, but at least it transforms.