In ggplot, geoms and stats must be paired in each layer added to the plot, so if you want both rasters/tiles and contour lines, you need to make two calls:
library(ggplot2)
ggplot(faithful, aes(x = eruptions, y = waiting)) +
stat_density2d(aes(fill = ..density..), geom = "raster", contour = FALSE) +
stat_density2d()
If you're aiming instead for filled contours, it's really hard without extending ggplot. Happily, that has already been done in the metR package:
ggplot(faithfuld, aes(eruptions, waiting, z = density)) +
metR::geom_contour_fill()
Note that I switched to faithfuld
, which already has the density computed, as geom_contour_fill
, like geom_contour
, is designed to work with raster data. It may be possible to get geom_contour_fill
to do the 2D density estimation for you, but it may be more straightforward to call MASS::kde2d
(what stat_density2d
uses) yourself and unpack the results to a data frame suitable for geom_contour_fill
.
# If we turn contouring off, we can use use geoms like tiles
immediately beforestat_density_2d(geom = "raster", aes(fill = stat(density)), contour = FALSE)
. It's not clear to me why, though. – Lyngbakr