[R] ggplo2: fixed extent greater than data?

hadley wickham h.wickham at gmail.com
Fri Nov 23 21:26:06 CET 2007

On 11/23/07, thegeologician <kmr at thegeologician.net> wrote:
> Hi everyone!
> I'm digging into ggplot for some while now, I must say it's great! But - as
> some others have posted before, and hadley knows very well himself - the
> documentation is lacking some bits...
> So I have to pose that question directly:
> I'd like to produce a series of maps with different data on, but exactly the
> same extent in each plot. Is there a way of switching the automatic extent
> (to the data of the last layer added) OFF? I'm trying something like:
> drawOverviewMap<-function(){
> p2<-ggplot(xlimits=c(2,20),ylimits=c(43,50))+coord_map(project="azequalarea")
>         p2<-p2+geom_path(data=wa,mapping=aes(x=x,y=y))
>         p2<-p2+geom_point(data=spts,mapping=aes(x=Lon,y=Lat))
>         return(p2)
> }
> If I plot this in cartesian coordinates, it will zoom to the extent of the
> country boundaries "wa", plus some extra space around it (since this is the
> dataset with the widest range). This extent can be fixed with the
> "limits=..." parameter. If I plot it in a map projection, as shown above, it
> zooms to the extent of the sample localities "spts" (plus extra space). ;-(

I think this is a bug in coord_map, as the limits set on the scales
are basically  ignored.  However, I'm not completely sure how to fix
this, as simply subsetting the data to be contained within those
bounds may drop off points that are necessary to correctly draw

Essentially the problem is that the limits are specified on the
unprojected data, and I don't know how to apply them to the projected
data (and you might not want to do that anyway, given that it could
produce non-linear boundaries).

> Additional question: is there a way of eliminating the extra spacing in a
> map projection? The "expand=c(0,0)" parameter seems not to work...

This is a bug.  The fix will be included in the next version of
ggplot, or you can fix the current version by running this code:

ScaleContinuous$new <- function(., name=NULL, limits=c(NA,NA),
breaks=NULL, labels=NULL, variable, trans="identity", expand=c(0.05,
0)) {
   if (is.null(breaks) && !is.null(labels)) stop("Labels can only be
specified in conjunction with breaks")

   .$proto(name=name, .input=variable, .output=variable,
limits=limits, .breaks = breaks, .labels = labels, .expand=expand)


More information about the R-help mailing list