Options to stat_density_2d

ggplot2

#1

Dear All,

Here is an example from ?geom_density_2d :

m <- ggplot(faithful, aes(x = eruptions, y = waiting)) +
geom_point() +
xlim(0.5, 6) +
ylim(40, 110)
m + geom_density_2d()

 m + stat_density_2d(aes(fill = ..level..), geom = "polygon")

My query is , what does geom =“polygon” do? Also what other geoms can I use which will make sense ?


#2

Functions like stat_density_2d and geom_density_2d are linked by default – calling one will call the other. When you call call geom_density_2d, ggplot2 creates a new plot layer using the “density_2d” geom and the “density2d” stat. The geom is essentially the same as the “contour” geom, which (obviously) plots contours from the data, and the “density2d” stat transforms the input data into density information. This creates the density contours that you see with the first bit of code.

The second bit, with geom = "polygon", still creates a layer that uses the “density2d” stat, but instead of the “density_2d” geom, it uses the “polygon” geom (normally accessed by the geom_polygon function). That geom, unsurprisingly, creates polygons, which can then be colored different colors by the fill aesthetic based on the ..level.. value derived by stat_density_2d.

As for what other geoms might make sense, the only ones that I’m aware of are raster and point, as shown in the documentation.


#3

Dear Nick,

Can you slow down and explain the process by which a contour gets converted to a polygon ? I think it is important to understand that.

Also what is the difference between density_2d and density2d?

And is there an order in which the polygons created by the contours get painted?


#4

From what I have dug into and understand of the ggplot2 code, the answer to both of these questions is “a :mage: did it”. Someone that is better versed in the code would have to answer; from my perspective, it just works.

They appear to be interchangeable. My reply used whichever was the default for the respective code.


#5

Without looking at the code at all I would simply assume that contours are converted into polygons by defining the region between two adjacent contours to be the interior of a polygon, such that n contours are converted into n polygons. As far as the order of painting, I believe that the polygons are non-overlapping so the order isn’t particularly relevant. As an experiment, I tried modifying the code from the original post with

m + stat_density_2d(aes(fill = …level…),color=“green”, size=2, geom = “polygon”)+
scale_fill_distiller(palette=“Accent”)+ geom_density_2d(color=“red”)

The resulting (appallingly unattractive) graph seems to confirm that the boundaries between the polygons are precisely the same as the contours.

It seems possible that perhaps each contour is treated as its own polygon, in which case the painting must be performed with the largest/most exterior contour/polygon painted first and the smallest/most interior contour/polygon painted last.