geom_statdensity2d with specific contours?

Viewed 918

My goal is to be able to use the geom_density2d() geom to draw contour levels on a scatter plot at user defined locations. Consider the following code:

library(ggplot2)
n = 100
df = data.frame(x = c(rnorm(n, 0, .5), rnorm(n, 3, .5)),
                y = c(rnorm(n, 1, .5), rnorm(n, 0, .5)))

ggplot(df, aes(x = x, y = y)) +
   geom_density2d() +
   geom_point() 

enter image description here

This produces a standard contour plot but there doesn't appear to be a way to manually control which contours get drawn. The optional parameters bins and h in can control the contour lines to some degree (being passed to kde2d from MASS I assume) but the resulting lines do not seem to be interpretable.

Ideally, I would be able to replicate the functionality of plot.kde from the ks library where these can be controlled via that cont argument.

library(ks)
est = kde(df)
plot(est, cont = c(50, 95))

enter image description here

1 Answers
Related