> I am having the problem that when adding stat_contour or stat_density2d
> the "upper" layer polygons are being obscured by lower ones.
Well, yes, later filled polygons will obscure previous ones. This is because ggplot2, like grid, operates on a "painter's model" of graphics (new overwrites old at any given location). The order in which layers are drawn can sometimes matter. Alpha transparency can be used to mitigate the problem. Try various fixed values of alpha (assuming the geom supports it) and use the one that looks the best to you.
(m <- ggplot(geyser, aes(x = duration, y = waiting)) +
geom_point() + xlim(0.5, 6) + ylim(40, 110))
m + stat_density2d(aes(fill = ..level..), geom="polygon")
m + stat_density2d(aes(fill = ..level..), geom="polygon", alpha = 0.2)
The colorbar issue is a side point that can be handled separately using guides().
A more mundane example of the painter's model:
DF <- data.frame(x = seq(10), y = seq(10))
# line overwrites points
ggplot(DF, aes(x = x, y = y)) + geom_point(size = 3, color = "orange") +
geom_line()
# points overwrite line
ggplot(DF, aes(x = x, y = y)) + geom_line() +
geom_point(size = 3, color = "orange")
# compromise
ggplot(DF, aes(x = x, y = y)) + geom_line() +
geom_point(size = 3, color = "orange", alpha = 0.6)