non-overlapping polygons in ggplot density2d

2019-05-07 01:21发布

问题:

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)))

回答1:

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 so I can close the issue.

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)))



回答2:

bpeter and user20650 solved the problem, but their answer can create another problem. On some plots, extending the x,y limits can make the plot too zoomed out to be useful.

Adding the following line should fix things (with appropriate x,y values):

coord_cartesian(ylim=c(-2, 2),xlim=c(0, 1))


标签: r ggplot2