Using ESRI shapefiles to create maps in R
Published:
R has plenty of plotting libraries, and you can combine them with open GIS data to build custom maps. In this post I’ll walk through a few.
The first step is getting hold of the shapefiles. DIVA-GIS is one source, but any site with open .shp files will do.
I’ll focus on administrative (country-level) data for Poland. Follow the DIVA-GIS link and you should see this screen: 
I’ll plot powiats and voivodeships which are first- and second-level administrative subdivisions in Poland.
Once you’ve downloaded and unzipped POL_adm.zip into your R working directory, you can use the scripts below to recreate the maps.
The simplest map uses the shapefiles on their own, with no background.
It’s hardly the prettiest map, but it does the job. Here’s the code: For something nicer, the ggmap package lets you overlay a shapefile onto Google Maps or OSM. Here I used the get_googlemap function; for a different background, use get_map with the appropriate arguments.
Code used to generate the map above: And last but not least, my favourite: an interactive map built with leaflet.
Snippet:
> sessionInfo()
R version 3.2.4 Revised (2016-03-16 r70336)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1
locale:
[1] LC_COLLATE=English_United Kingdom.1252 LC_CTYPE=English_United Kingdom.1252
[3] LC_MONETARY=English_United Kingdom.1252 LC_NUMERIC=C
[5] LC_TIME=English_United Kingdom.1252
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] rgdal_1.1-7 ggmap_2.6.1 ggplot2_2.1.0 leaflet_1.0.1 maptools_0.8-39
[6] sp_1.2-2
loaded via a namespace (and not attached):
[1] Rcpp_0.12.4 magrittr_1.5 maps_3.1.0 munsell_0.4.3
[5] colorspace_1.2-6 geosphere_1.5-1 lattice_0.20-33 rjson_0.2.15
[9] jpeg_0.1-8 stringr_1.0.0 plyr_1.8.3 tools_3.2.4
[13] grid_3.2.4 gtable_0.2.0 png_0.1-7 htmltools_0.3.5
[17] yaml_2.1.13 digest_0.6.9 RJSONIO_1.3-0 reshape2_1.4.1
[21] mapproj_1.2-4 htmlwidgets_0.6 labeling_0.3 stringi_1.0-1
[25] RgoogleMaps_1.2.0.7 scales_0.4.0 jsonlite_0.9.19 foreign_0.8-66
[29] proto_0.3-10
