I am creating a figure where I have a line and confidence bands around it. To do this, I am using both geom_line
and geom_ribbon
in ggplot2
Try to keep the colour outside aes
, then it won't show on legend:
h1 + geom_ribbon(aes(ymin=lower, ymax=upper, x=x), colour = "red", alpha = 0.3)
If you want to show the color on the legend, you probably have to resort to adding a few additional geom_line
s. Don't use a color in geom_ribbon
and then add upper
and lower
lines.
h2 <- h1 + geom_ribbon(aes(ymin=lower, ymax=upper, x=x), alpha = 0.3) +
geom_line(aes(x=x, y = lower, color = "bands")) +
geom_line(aes(x=x, y = upper, color = "bands"))
EDIT: You can additionally use a fill
scale.
h1 <- ggplot(plotdata) + geom_line(aes(y=y, x=x, colour = "sin", fill="sin"))
h2 <- h1 + geom_ribbon(aes(ymin=lower, ymax=upper, x=x, fill="bands"), alpha = 0.3) +
geom_line(aes(x=x, y = lower, color = "bands")) +
geom_line(aes(x=x, y = upper, color = "bands"))
h3 <- h2 + scale_colour_manual(name='', values=c("bands" = "grey", "sin" = "blue")) +
scale_fill_manual(name = '', values=c("bands" = "grey12", "sin" = "grey"))
grid.arrange(h1, h2, h3)
You could also set "bands" = "transparent"
in the color statement, if you don't want the (barely visible) grey line.
You can make to separate legends - one for the color of line and one for the fill of the ribbon. Then with scale_...
set the names for the legend to blank. Only problem is that legend keys will be separated.
ggplot(plotdata) + geom_line(aes(y=y, x=x, colour = "sin"))+
geom_ribbon(aes(ymin=lower, ymax=upper, x=x, fill = "band"), alpha = 0.3)+
scale_colour_manual("",values="blue")+
scale_fill_manual("",values="grey12")