1
votes

Using contours with stat_density2d gives error:

ggplot(faithful, aes(x = eruptions, y = waiting, fill = ..density..)) + 
  stat_density2d(geom = "tile")

Don't know how to automatically pick scale for object of type function. Defaulting to continuous. Error in is.finite(x) : default method not implemented for type 'closure'

Using contour = F plots without error. What is the issue?

1
In the documentation here, there's a comment # If we turn contouring off, we can use use geoms like tiles immediately before stat_density_2d(geom = "raster", aes(fill = stat(density)), contour = FALSE). It's not clear to me why, though.Lyngbakr
To draw contours, you need breaks, whereas tiles/rasters are continuous. One stat/geom will never plot more than one geom, so if you want colors and lines, make two calls. (Lines second, so they'll be on top.) If you want filled lines, check out the metR package, which does some really cool stuff that way.alistaire
@alistaire can you post as answer?qwr

1 Answers

2
votes

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.