Geom_statdensity2d with special contours?

My goal is to use geometry geom_density2d()to draw outlines on a scatterplot in user-defined places. 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 creates a standard outline graph, but there seems to be no way to manually control which outlines are drawn. The optional parameter bits and h inside can to some extent control the contour lines (passed to kde2d from MASS, which I assume), but the resulting lines do not seem interpreted.

Ideally, I could reproduce the functionality of plot.kde from the ks library, where they can be controlled with this cont argument.

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

enter image description here

+4
source share
1

, . , . , . , ggplot. , , ggplot_build(g)$data[1]. level. , . myfun() , . .

setseed(111)
mydf = data.frame(x = c(rnorm(100, 0, .5), rnorm(100, 3, .5)),
                  y = c(rnorm(100, 1, .5), rnorm(100, 0, .5)))

g <- ggplot(mydf, aes(x = x, y = y)) +
            geom_density2d() +
            geom_point()

### Get a list containing data used for drawing g.

temp <- as.data.frame(ggplot_build(g)$data[1])

### Check which levels you have in g

ind <- unique(temp$level)

ind
#[1] 0.02 0.04 0.06 0.08 0.10 0.12 0.14 0.16 0.18 0.20


myfun <- function(...){
               ana <- c(...)
               foo <- subset(temp, level %in% ana)

               g <- ggplot() +
               geom_path(data = foo, aes(x = x, y = y, group = group), colour = "red")

               print(g)

               }

### Run myfun by specify levels you want.
myfun(0.02, 0.10, 0.18)

enter image description here

0

All Articles