title: Controlling plot order for visual objects with multiple geometries in ggplot2
body: <p>I want ggplot to plot in a specific order to control what is visible when objects overlap.  Each data row maps to a composite of 2 geometry layers - the particulars of the plot require this.  I've been using a loop to do this, but it's very slow.  I wonder if there's a better way?  e.g.</p>
  
  <pre><code>d = data.frame(x=c(1,5,2,2,4,2), y=c(1,1,4,3,3,5), grp=c(1,1,1,2,2,2))
  
  ggplot(d, aes(x, y, group=grp)) + 
    geom_polygon(aes(fill = factor(grp))) +
    geom_line(size=1)
  </code></pre>
  
  <p><a href="https://i.stack.imgur.com/Ek3ao.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ek3ao.png" alt="enter image description here"></a></p>
  
  <p>Each polygon line should plot with its polygon - so e.g. the red polygon's line should be obscured by blue's polygon.  Is there any way to achieve this without looping when both <code>geom_polygon</code> and <code>geom_line</code> use the same dataset?</p>
  
  <hr>
  
  <p><strong>Edit:</strong> looping methods..</p>
  
  <p>Here are loop methods I've used.  Added a better dataset for comparing performance.  Both take about 5.6s to run on my machine.  By comparison the typical approach (<code>ggplot(d, aes(x, y, fill=factor(grp))) + geom_polygon() + geom_line(size=1)</code>) takes 0.45s.</p>
  
  <pre><code>d = data.frame(x = sample(-30:30,99,rep=T) + rep(sample(1:100,33),each=3),
                 y = sample(-30:30,99,rep=T) + rep(sample(1:100,33),each=3),
                 grp = rep(1:33,each=3))
  
  # Method 1 - for loop
  p = ggplot()
  for(g in unique(d$grp)){
    dat = subset(d, grp == g)
    p = p + geom_polygon(data=dat, aes(x, y, fill = factor(grp))) + 
      geom_line(data=dat, aes(x, y), size=1)
  }
  print(p)
  
  # Method 2 - apply
  ggplot() + lapply(unique(d$grp), FUN=function(g){
    dat = subset(d, grp == g)
    list(geom_polygon(data=dat, aes(x, y, fill = factor(grp))),
         geom_line(data=dat, aes(x, y), size=1))
  })
  </code></pre>
  
  <p><a href="https://i.stack.imgur.com/LObv1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LObv1.png" alt="enter image description here"></a></p>