I've seen some examples when constructing a heatmap of having the fill
variable set to ..level..
.
Such as in this example:
library(MASS)
ggplot(geyser, aes(x = duration, y = waiting)) +
geom_point() +
geom_density2d() +
stat_density2d(aes(fill = ..level..), geom = "polygon")
I suspect that the ..level..
means that the fill
is set to the relative amount of layers present? Also could someone link me a good example of how to interpret these 2D-density plots, what does each contour represent etc.? I have searched online but couldn't find any suitable guide.
the
stat_
functions compute new values and create new data frames. this one creates a data frame with alevel
variable. you can see it if you useggplot_build
vs plotting the graph:The
..level..
tells ggplot to reference that column in the newly build data frame.Under the hood, ggplot is doing something similar to (this is not a replication of it 100% as it uses different plot limits, etc):
And also calling
contourLines
to get the polygons.This is a decent introduction to the topic. Also look at
?kde2d
in R help.Expanding on the answer provided by @hrbrmstr -- first, the call to
geom_density2d()
is redundant. That is, you can achieve the same results with:Let's consider some other ways to visualize this density estimate that may help clarify what is going on:
Notice, however, we can no longer see the points generated from
geom_point()
.Finally, note that you can control the bandwidth of the density estimate. To do this, we pass
x
andy
bandwidth arguments toh
(see?kde2d
):Again, the points from
geom_point()
are hidden as they are behind the call tostat_density2d()
.