I am trying to recreate a filled contourplot in ggplot2, but the polygons created result in some ugly clipping:
Consider the sample data:
require(ggplot2)
require(MASS)
x <- runif(10000)
y <- rnorm(10000)
dt <- data.frame(x=x, y=y)
Using filled.contour
, I can get a density plot using
k <- kde2d(x,y)
filled.contour(k,xlim=c(0,1), ylim=c(-3,3))
However, using ggplot the density polygons get cut where they intersect some boundary of the density estimate.
p <- ggplot(dt, aes(x=x, y=y))
dens <- stat_density2d(aes(fill=..level..), geom="polygon")
p + dens
Solution
The comment by user20650 indeed solved the issue, which seemed to be that runif has support on [0,1], but the kernel density estimates are a bit beyond that:
Here is his solution for future reference:
p <- ggplot(dt, aes(x=x, y=y))
dens <- stat_density2d(aes(fill=..level..), geom="polygon")
p + dens + scale_x_continuous(limit=c(-0.1, 1.1)))