Skip to content

Instantly share code, notes, and snippets.

Created December 8, 2016 09:50
Show Gist options
  • Save anonymous/178c2dd236e9a7b18a19a62ab44f4dfd to your computer and use it in GitHub Desktop.
Save anonymous/178c2dd236e9a7b18a19a62ab44f4dfd to your computer and use it in GitHub Desktop.
polygon clipping in ggplot
usq = data.frame(x=c(0,1,1,0),y=c(0,0,1,1))
pts1 =
structure(list(x = c(-0.380226816911908, -0.368506824640174,
0.276092750305198, 0.281952746441065, -0.350926836232573, -0.362646828504307,
-0.720106592792195), y = c(-0.287042131866309, 0.237226050260459,
0.276546163919967, 0.532126902706766, 0.578000368642859, 1.06294843711012,
1.06294843711012)), .Names = c("x", "y"), row.names = c(NA, -7L
), class = "data.frame")
polys = SpatialPolygons(list(Polygons(list(Polygon(pts1)),ID=1),Polygons(list(Polygon(usq)),ID=2)))
plot(polys)
fp = fortify(polys)
# this works
ggplot(fp,aes(x=long,y=lat,colour=id, group=id)) + geom_polygon(fill=NA)
# this mashes the clipped polygon:
ggplot(fp,aes(x=long,y=lat,colour=id, group=id)) + geom_polygon(fill=NA) +xlim(c(-0.4,1.2))+ylim(c(-0.4,1.2))
# this works:
ggplot(fp,aes(x=long,y=lat,colour=id,group=id,fill=id)) + geom_polypath()
# this fails with a "non-finite" error:
ggplot(fp,aes(x=long,y=lat,colour=id,group=id,fill=id)) + geom_polypath() +xlim(c(-0.4,1.2))+ylim(c(-0.4,1.2))
# using real data
require(spdep)
example(columbus)
plot(columbus, xlim=c(8.9,9.6), ylim=c(12.0,12.8))
# mashed up
ggplot(columbus,aes(x=long,y=lat,group=group)) + geom_polygon(fill=NA, colour="black") + xlim(c(8.9,9.6)) + ylim(c(12.0,12.8))
@cpsievert
Copy link

xlim()/ylim() sets the limits of the scale, not the limits of the coordinate system (you need to use coord_cartesian())

Please fix or remove so that future visitors don't wind up thinking that ggplot2 is the failure here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment