Using R — Working with Geospatial Data (and ggplot2)

This is a follow-up blog-post to an earlier introductory post by Steven Brey: Using R: Working with Geospatial Data. In this post, we’ll learn how to plot geospatial data in ggplot2. Why might we want to do this? Well, it’s really about your personal taste. Some people are willing to forfeit the fine-grained control of base graphics in exchange for the elegance of a ggplot. The choice is entirely yours.

To get started, we’ll need the ggplot2 package and some data! The dataset we’ll look at are shapefiles defining watersheds in Washington state.

NOTE:  Check the Department of Ecology GIS data page if any of the links are unavailable.

Loading libraries and data

Transforming the data

Thus far, we haven’t done anything radically different than before, but in order to prepare the data for plotting in a ggplot, we’ll have to do a couple manipulations to the structure of the data. ggplot2 will only work with a data.frame object, so our object of class of SpatialPolygonsDataFrame will not be appropriate for plotting. Let’s write some code and discuss why this kind of transformation is necessary.

What does all this code mean and why do we need it? Let’s go through this line by line.

Here we are appending to the data an extra column called “id”. This column will contain the rownames so that we define an explicit relationship between the data and the polygons associated with that data.

Fortify? What does that even mean? A quick search on the internet will yield some helpful documentation. (See fortify.sp documentation). Basically, fortify take two arguments: model, which will consist of the SpatialPolygonsDataFrame object we wish to convert and region, the name of the variable by which to split regions. If all goes according to plan, some magic happens and we get a data.frame, just like we wanted… well, not quite. If you inspect this data.frame, you’ll notice it appears to be missing some critical information. Fret not! Using the relationship we created earlier, we can merge these two datasets with the following command.

And viola! Now that we’ve created a data.frame that ggplot2 likes, we can begin plotting. Before we get to plotting, let’s take a quick look at this new data.frame we’ve created.

Your first ggplot

If you’re coming from base graphics, some of the syntax may appear intimidating, but’s it’s all part of the “grammar of graphics” after which ggplot2 is modeled. You’ll notice a graph is built layer by layer, beginning with the data and the mapping of data to “aesthetic attributes”. We’ll add “geoms” or geometric objects and perhaps we’ll compute some statistics. We may also want to adjust the scale or coordinate system. All this can be added in a very modular fashion; this is one of the key advantages to using ggplot2. So, enough talk, let’s make a plot!


Alright, so we have created our first ggplot. Looks pretty spiffy, right? We started by passing a data.frame to the function ggplot. From there, we added some aesthetic mappings. x and y are fairly self-explainatory, group = group simply identifies the groups of coordinates that pertain to individual polygons and fill = WRIA_NM will attempt to assign an appropriate color scale to data based on the “WRIA_NM” column. Next, we added several “geoms” including polygons and paths. The polygons are the brightly colored shapes you see, and the path is the white outline around each shape. scale_fill_hue() changes the properties of the colors displayed and theme() can be used to change a number of properties; in this case I chose not to display a legend or axis labels since they add very little to the plot. Lastly, coord_equal() fixes the aspect ratio between the horizontal and vertical scales.

Manipulating spatial objects

Now, let’s get some practice working with spatial objects. For this exercise, we will subset the data and observe watersheds in the Puget Sound region. For ease of access, we’ll cut out some the data we don’t particularly care about and rename some of the columns to be more descriptive.


Since the plot was simply a “sanity check” of sorts, I decided to use base graphics for a quick peek. Perhaps you should try making it into a ggplot.

Before wrapping up this exercise, lets transform the subsetted dataset so it’s ready to be used by ggplot2.

More ggplots

Onto the more fun analysis. While this dataset is fairly limited in information, it does contain some numerical values that might be worth investigating. Let’s get some information regarding the area of Washington’s watersheds. You’ll find that ggplot2 makes it very easy to visualize this kind of information.


That seemed pretty painless. All we had to do was set the fill aesthetic to the region area and add scale_fill_gradient() to define a continuous color scale; ggplot seemed to handle everything else for us. Notice in the previous ggplot that I set fill = WRIA_NM, or the watershed name. This information was identified as a categorical variable and regions were therefore filled with variety of colors. In the script above, I passed fill = area. If I did not add scale_fill_gradient(), I would have recieved the following error message: Error: Continuous value supplied to discrete scale. This ggplot expected a categorical variable, so it became necessary to add the scale_fill_gradient() layer.

Say, the way this ggplot colors the regions is actually kind of counter- intuitive; light regions for larger areas and dark regions for smaller areas? Doesn’t make much sense if you ask me. Let’s do something about that. Since this is Washington, we’ll don some UW spirit. Hope you like purple and gold! (Apologies to any WSU fans out there.)


Okay, so the purple and gold might be a bit obnoxious, but you get the idea. Let’s just color the largest of the watersheds. Before we get to that, let’s inspect the data to determine exactly which one that is. You can already sort of guess based on the size and color of the regions, but let’s be sure.

So supposedly we have identified Washington’s largest watershed. Let make another ggplot to see what this watershed looks like. Remember, ggplot2 only likes data.frames, so we’ll have to mess around with the data.

If we’re going to do this kind of transformation every time we make a ggplot, perhaps we can make a method to reduce coding time. Alas, that will wait for another day. Now we plot!


That seemed like a lot of trouble to go through just to find the largest area. Can we do that without creating an entirely new spatial object? Of course we can!


Using ggmap

The last thing I’ll describe in this post is the function and use of ggmap. This library is used for visualizing spatial data with the likes of Google Maps using ggplot2. A quick example is provided below.


Final remarks

While these plots may look “nicer”, ggplot2 has a couple of disadvantages. Perhaps most glaring is the increase in computing time. base graphics are built to be fast. Generally speaking, visualizing geospatial data is not the fastest process in the world, but using base vs. ggplot2 can be the difference between 0.5 seconds and 10 seconds. So if you’re producing graphics on-they-fly, stick with base, but if you’re looking to create publication quality graphics, ggplot2 is certainly worth learning.

Read more

Learn more about plotting spatial data using ggplot2 at these sources:


This entry was posted in Data Visualization, R and tagged , . Bookmark the permalink.

3 Responses to Using R — Working with Geospatial Data (and ggplot2)

  1. Edward Vanden Berghe says:

    Nice tutorial, thanks!

    It seems the example GIS data has been moved to





  2. Salikhov Marcel says:

    source shapefile is not available on ftp server, so the code is not reproducible by third party user

  3. Dave Currie says:

    Good introduction,  thanks.  One important issue that potential users of ggmap should be aware of is that the only available projection is google mercator.  Base graphics (as well as sp, raster, and rastervis) allow you to use any map projection you choose which I find to be critical for proper presentation in many applications, particularly polar regions.  On the other hand, ggmap does a good job of annotating the plot with graticules and legends, something the base graphics package does not make very easy.