简体   繁体   English

使用ggplot stat_density_2d在levelplot中破碎的多边形

[英]Broken polygons in levelplot using ggplot stat_density_2d

Creating a levelplot using ggplot 's stat_density_2d I get " broken " polygons. 使用ggplotstat_density_2d创建一个水平stat_density_2d我得到了“ 破碎 ”的多边形。 For example, the outer one in the example below. 例如,以下示例中的外部。

How can I fix this, to get a smooth form? 我如何解决这个问题,以获得一个流畅的表格?

在此处输入图片说明

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

To build on @hrbrmstr's answer (which, at least on my machine, lops off one data point because the x scale isn't sufficiently wide), a slightly more involved approach would be to get the limits of the data, set the scale limits, then reset the plot limits back to the original range: 为了建立@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)

Output: 输出:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM