5

We may want to define some global aes() for a ggplot() graphics, but exclude them in some layers. For instance suppose the following example:

foo <- data.frame(x=runif(10),y=runif(10))
bar <- data.frame(x=c(0,1),ymin=c(-.1,.9),ymax=c(.1,1.1))
p <- ggplot(foo,aes(x=x,y=y))+geom_point()

Everything is good. However when trying to add the ribbon:

p <- p + geom_ribbon(data=bar, aes(x=x,ymin=ymin,ymax=ymax), alpha=.1)
# Error: Discrete value supplied to continuous scale

This error happens because we have already defined y as a part of global aes() that applies also to the geom_ribbon(), but the bar does not have it.

I have found two possibilities to escape this error, one of them is to remove y=y from the original ggplot(foo,aes(x=x,y=y)), however every time in the future I need to draw something I should add y=y to the aes() that is not good.

The other possibility is to add a fake y column to bar:

bar = cbind(bar, y=0)
p <- p + geom_ribbon(data=bar, aes(x=x,ymin=ymin,ymax=ymax), alpha=.1)

enter image description here

Now works good. However I don't like acting so, as it's a fake variable. Is there any way to temporarily disable the already defined aes() in ggplot() when calling the geom_ribbon()?

Maarten Bodewes
  • 90,524
  • 13
  • 150
  • 263
Ali
  • 9,440
  • 12
  • 62
  • 92
  • 2
    How about `aes(y=NULL,x=x,ymin=ymin,ymax=ymax)`? – Ernest A Dec 11 '12 at 15:18
  • 2
    As @ErnestA said, you can unmap aesthetics by setting them to `NULL` in a particular layer. – joran Dec 11 '12 at 15:26
  • @ErnestA why not put your comment as an answer ? – agstudy Dec 11 '12 at 15:28
  • @agstudy I'm pretty busy at the moment. Feel free to write an answer yourself. – Ernest A Dec 11 '12 at 15:38
  • 2
    Try `inherit.aes = FALSE` when using a new data set. See answers and comments [here](http://stackoverflow.com/questions/5415132/object-not-found-error-with-ggplot2-when-adding-shape-aesthetic) and [here](http://stackoverflow.com/questions/10930737/ggmap-with-geom-map-superimposed) – Sandy Muspratt Dec 11 '12 at 19:47

1 Answers1

5

As said in the comments by @ErnestA, we can unmap the aesthetics by setting them to NULL

      aes(y=NULL,x=x,ymin=ymin,ymax=ymax)

PS: For the legend you can now override aesthetic by aes.override

agstudy
  • 119,832
  • 17
  • 199
  • 261