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


homies1

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) 

ggmap(
	get_googlemap(
		center=c(-3.17486, 55.92284), #Long/lat of centre, or "Edinburgh"
		zoom=14, 
		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 = “satellite”

maptype = "roadmap"

maptype = “roadmap”

maptype = "terrain"

maptype = “terrain”

We can also obtain a map from OpenStreetMap:

libary (ggmap) 

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(
	get_googlemap(
		center=c(-3.17486, 55.92284), 
		zoom=16, 
		maptype='hybrid', 
		scale = 2), 

		size = c(600, 600),
		extent='normal', 
		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)

homies1homies2

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!

Advertisements

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

  1. Hi, I tried the below code
    library(ggmap)
    aus<- qmap('australia')

    and encountered the following error.. Please let me know what could be done to rectify this

    Error in download.file(url, destfile = destfile, quiet = !messaging, mode = "wb") :
    cannot open URL 'http://maps.googleapis.com/maps/api/staticmap?center=55.92284,-3.17486&zoom=14&size=%20640×640&scale=%202&maptype=satellite&sensor=false&#039;
    In addition: Warning message:
    In download.file(url, destfile = destfile, quiet = !messaging, mode = "wb") :
    cannot open: HTTP status was '403 Forbidden'

  2. Hi,
    I’ve also tried the above Austrlia example as well as your code, and every time I get the same error:
    “Error in message(paste0(“Map from URL : “, url)) :
    could not find function “paste0″”

    Do you know what is the problem? Thanks a lot in advance, and thanks for the great post!

  3. Working example with ggmap? I’m afraid not, I have just started working (trying to work) with the package and I keep getting the same error message.
    After googling it some more, I get the idea that it is related to an older version of R I have (2.14.1), and which I don’t seem to be able to upgrade for my version of Linux.

      • Ah, sure. I’ve copy-pasted your first code, just edited the path where to save the plot when I got the error. I get the same error if I simply try to get the map of The Netherlands with
        my_map <- qmap('netherlands').

    • Yes, I didn’t copy the “library” part, so that was fine. There were no problems reported when installing and loading the package. Now I find that a plot has been made. That is, I have a “ggmap Temp.png” plot of the Netherlands in my folder, even though I still get the same “paste0…” error.

      • If you haven’t used the paste0 function yourself it must be within the ggmap package. Since it works in my version of R I think that it might be that some functions (i.e. paste0) are have since been depreciated. Is there no way you can update your R?

  4. Yes, unfortunately that is my conclusion as well. I’ve tried the “usual” way of upgrading and that doesn’t work, due to some ” unmet dependencies”. There might be some compatibility issues and I am still trying to find out how to fix it.
    Thanks for replying!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s