Skip to content

Instantly share code, notes, and snippets.

@barryrowlingson
Forked from anonymous/ggfail.R
Last active January 29, 2018 15:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save barryrowlingson/79f0964777496e78c57d6be825ea68f3 to your computer and use it in GitHub Desktop.
Save barryrowlingson/79f0964777496e78c57d6be825ea68f3 to your computer and use it in GitHub Desktop.
polygon clipping in ggplot
library(sp)
library(rgdal)
library(ggplot2)
library(spdep)
library(ggpolypath)
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
columbus = rgdal::readOGR(system.file("etc/shapes/",package="spdep")[1],"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

cpsievert commented Jan 29, 2018

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 @barryrowlingson 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