Reputation: 9830
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)
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()
?
Upvotes: 5
Views: 2357
Reputation: 121568
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
Upvotes: 6