Tomas Alonso Rehor Tomas Alonso Rehor - 8 days ago 14
R Question

Plotting SHP file R

Im trying to read and plot a shp file from Argentina to create a custom choropleth. Im following exactly all code examples to load and plot this map but nothing is working.

The R red sign stays on as like R is still processing information, but never plots anything or stops working.

This is my screen when I run to "plot" and then says Rstudio stopped working. Any idea why it could be not working?

enter image description here

Answer

First, ggplot2 seems to be able to handle this pretty well:

library(rgdal)
library(ggplot2)

arg_shp <- readOGR("../data/arg_adm/ARG_adm1.shp", "ARG_adm1")

arg_shp_map <- fortify(arg_shp)

gg <- ggplot() 
gg <- gg + geom_map(data=arg_shp_map, map=arg_shp_map, 
                    aes(long, lat, map_id=id),
                    color="#2b2b2b", size=0.15, fill=NA)
gg <- gg + coord_map()
gg <- gg + ggthemes::theme_map()
gg

enter image description here

Since you're using a GADM file, you don't really need to use an external shapefile tho, just use getData():

library(maptools)
library(raster)

arg_adm <- getData('GADM', country='ARG', level=1)
arg_adm_map <- fortify(arg_adm)

(same ggplot2 code from above works, just sub out the variable name).

I can't get the base plotting system to plot this either (on any graphics device). I think there are some complex polygons in part of the coastline. We can deal with that pretty easily tho:

library(maptools)
library(raster)
library(rgeos)
library(magrittr)
library(sp)

arg_adm <- getData('GADM', country='ARG', level=1)

gSimplify(arg_adm, 0.01, topologyPreserve=TRUE) %>% 
  SpatialPolygonsDataFrame(dat=arg_adm@data) -> new_arg

plot(new_arg, lwd=0.25)

enter image description here

(base plot default margins and the way it deals with projections result in that different-sized map)

Unless you need the border precision, simplifying shapefiles like this can save a great deal of plotting time. You can use the optimized shape in ggplot2 as well, along with an Argentina-tailored map projection:

new_arg_map <- fortify(new_arg)

gg <- ggplot() 
gg <- gg + geom_map(data=new_arg_map, map=new_arg_map, 
                    aes(long, lat, map_id=id),
                    color="#2b2b2b", size=0.15, fill=NA)
gg <- gg + ggalt::coord_proj("+proj=aeqd +lat_0=-37.869859624840764 +lon_0=-66.533203125")
gg <- gg + ggthemes::theme_map()
gg

enter image description here

(Though, coord_map()'s default Mercator projection is pbly gd enough for most uses)