non-overlapping polygons in ggplot density2d

2019-05-07 01:17发布

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

solution

标签: r ggplot2
2条回答
姐就是有狂的资本
2楼-- · 2019-05-07 01:48

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))
查看更多
再贱就再见
3楼-- · 2019-05-07 02:12

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

solution

查看更多
登录 后发表回答