#13 Mapping in R: Representing geospatial data together with ggplot

February 1, 2013

(This article was first published on Darren Wilkinson » R, and kindly contributed to R-bloggers)


I have been trawling around for a while now trying to find a simple and understandable way of representing geospatial data in R, whilst retaining the ability to manipulate the visualisation in ggplot. After much searching I came across some articles which got me to a working product only after a lot of ball ache. All the coding is done in R, so if you don’t know what it is click here. I keep the code simple, mainly because I don’t need it to be more complex for my purposes, but it also helps newbies like me learn the syntax faster.

GGMAP is a package that was developed by David Kahle and Hadley Wickham (Hadley being the guy behind ggplot2). If you want more detail see David’s slides from the 8th International R User Conference.

1.0 Fetching a Map

Maps may be brought into R from a number of sources, the two main ones are GoogleMaps and OpenStreetMap. The code needed to fetch the map is slightly different depending on where you want the data from. Below are some examples:

libary (ggmap) 

		center=c(-3.17486, 55.92284), #Long/lat of centre, or "Edinburgh"
		maptype='satellite', #also hybrid/terrain/roadmap
		scale = 2), #resolution scaling, 1 (low) or 2 (high)
		size = c(600, 600), #size of the image to grab
		extent='device', #can also be "normal" etc
		darken = 0) #you can dim the map when plotting on top

ggsave ("/Users/s0679701/Desktop/map.png", dpi = 200) #this saves the output to a file

This outputs the following files:

maptype = “satellite”

maptype = “roadmap”

maptype = “terrain”

We can also obtain a map from OpenStreetMap:

libary (ggmap) 

	get_openstreetmap (
	bbox = c(-3.16518, 55.91899, -3.18473, 55.92716), 
	format = "png"

ggsave ("/Users/s0679701/Desktop/map.png", dpi = 200) #this saves the output to a file

You may receive the following error:

 Error: map grabbing failed - see details in ?get_openstreetmap.
In addition: Warning message:
In download.file(url, destfile = destfile, quiet = !messaging, mode = "wb") :
  cannot open: HTTP status was '503 Service Unavailable'

This is because the OpenMapServer has issues, and so you just need to be lucky! Hence why there is no OpenStreetMap for this example…. yet.

2.0 Plotting on a Map

You can plot any [x,y, +/- z] information you’d like on top of a ggmap, so long as x and y correspond to longitudes and latitudes within the bounds of the map you have fetched. To plot on top of the map you must first make your map a variable and add a geom layer to it. Here is an example:

libary (ggmap) 

#Generate some data
long = c(-3.17904, -3.17765, -3.17486, -3.17183)
lat = c(55.92432, 55.92353, 55.92284, 55.92174)
who = c("Darren", "Rachel", "Johannes", "Romesh")
data = data.frame (long, lat, who)

map = ggmap(
		center=c(-3.17486, 55.92284), 
		scale = 2), 

		size = c(600, 600),
		darken = 0)

map + geom_point (
		data = data,
		aes (
			x = long, 
			y = lat, 
			fill = factor (who)
		pch = 21, 
		colour = "white", 
		size = 6
		) +

	scale_fill_brewer (palette = "Set1", name = "Homies") +

	#for more info on these type ?theme()	
	theme ( 
		legend.position = c(0.05, 0.05), # put the legend INSIDE the plot area
		legend.justification = c(0, 0),
		legend.background = element_rect(colour = F, fill = "white"),
		legend.key = element_rect (fill = F, colour = F),
		panel.grid.major = element_blank (), # remove major grid
		panel.grid.minor = element_blank (),  # remove minor grid
		axis.text = element_blank (), 
		axis.title = element_blank (),
		axis.ticks = element_blank ()

ggsave ("/Users/s0679701/Desktop/map.png", dpi = 200)


This simple code should be enough to get you going making your own plots. If you have any questions about this code or your own, then please don’t hesitate with getting in touch via the comments below.

Happy Mapping!

To leave a comment for the author, please follow the link and comment on their blog: Darren Wilkinson » R.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...

If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.


Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)