[R-sig-Geo] Plotting SpatialPolygonsDataFrame using ggplot2

Paul Hiemstra p.hiemstra at geo.uu.nl
Tue Apr 27 11:17:28 CEST 2010

Hi people,

I have a question regarding plotting a SpatialPolygonsDataFrame using 
ggplot2. To convert the SPDF to a dataframe with the coordinates I 
already use the excellent solution provided by Hadley in:


Some example code:

x <- readShapePoly(system.file("shapes/sids.shp", package="maptools")[1],
      IDvar="FIPSNO", proj4string=CRS("+proj=longlat +ellps=clrk66"))
dum = fortify(x, region = "CNTY_ID")
ggplot(dum, aes(x = long, y = lat)) + geom_path()

My problem is that not only the counties are drawn, but also lines 
between the end point of one countie polygon and the beginning of the 
next. I solve this right now by adding the counties I want to plot one 
by one using:

p + geom_path(subset(dum, id == 1) + geom_path(subset(dum, id == 2) + 
... etc

This is of course a solution, but not an elegant one. Creating a new 
ggplot object like:

unique_ids = unique(dum$id)
bla = ggplot(subset(dum, id == unique_ids[1]), aes(x =long, y = lat)) + 
for(id in unique_ids[2:length(unique_ids)]) {
       bla = bla + layer(data = subset(dum, id == id), mapping = aes(x 
=long, y = lat), geom = "path")
Has exactly the same problem as using ggplot(dum, aes(x = long, y = 
lat)) + geom_path(). I browsed the net and the maling list and could not 
find the answer, only references to the fortify() solution of Hadley.

Anybody have an idea for an elegant solution to the problem?


Drs. Paul Hiemstra
Department of Physical Geography
Faculty of Geosciences
University of Utrecht
Heidelberglaan 2
P.O. Box 80.115
3508 TC Utrecht
Phone:  +3130 274 3113 Mon-Tue
Phone:  +3130 253 5773 Wed-Fri

More information about the R-sig-Geo mailing list