使用 ggplot stat_density_2d 在 levelplot 中断开多边形

Broken polygons in levelplot using ggplot stat_density_2d

使用 ggplotstat_density_2d 创建水平图我得到“broken”多边形。例如,下例中的外部。

如何解决这个问题,以获得平滑的表格?

set.seed(0)
n <- 50
d <- data.frame(x = rnorm(n, -.7, .5), 
                y = rnorm(n, 0, .8))
ggplot(d, aes(x, y)) + 
  geom_point() +
  stat_density_2d(aes(fill = ..level..), alpha=.1, geom = "polygon") 

以@hrbrmstr 的答案为基础(至少在我的机器上,由于 x 尺度不够宽,它会删掉一个数据点),一种稍微复杂一点的方法是获取数据的限制,设置比例限制,然后将绘图限制重置回原始范围:

g <- ggplot(d, aes(x, y)) + 
  geom_point() +
  stat_density_2d(aes(fill = ..level..), alpha=.1, geom = "polygon")

dat_lims <- lapply(d, function(v) c(min(v), max(v)))
plot_lims <- ggplot_build(g)$panel$ranges[[1]][c("x.range", "y.range")]

g +
  scale_x_continuous(limits = dat_lims$x * 1.1) + 
  scale_y_continuous(limits = dat_lims$y * 1.1) +
  coord_cartesian(xlim = plot_lims$x.range, ylim = plot_lims$y.range)

输出: