I find very convenient to name layers of my graph. It permits to remove a layer easily by its names. For example:
g <- ggplot() + geom_point(aes(x=c(0, 1), y=c(2, 3), size = c(2, 5)), shape=19)
names(g$layers)[length(g$layers)] <- "Circles"
g <- g + geom_point(aes(x=c(4, 6), y=c(2, 7), size = c(2, 6)),
shape=15, show.legend = TRUE)
names(g$layers)[length(g$layers)] <- "Squares"
# Both are displayed
g
# I remove the circles
g$layers[names(g$layers) == "Circles"] <- NULL
g
So it seems to work fine.
But here the points in the legend do not appear if I name the first layer. I do something wrong ?
Thanks
# It works
g <- ggplot() + geom_segment(aes(x=27, y=0, xend = 27, yend = 1), linewidth = 1)
g + geom_point(aes(x=c(28, 30), y=c(0.3, 0.4), size = c(2, 3)),
show.legend = TRUE)
# It does no work
g <- ggplot() + geom_segment(aes(x=27, y=0, xend = 27, yend = 1), linewidth = 1)
names(g$layers)[length(g$layers)] <- "Base"
g + geom_point(aes(x=c(28, 30), y=c(0.3, 0.4), size = c(2, 3)),
show.legend = TRUE)