ggplot density2d 中的非重叠多边形
non-overlapping polygons in ggplot density2d
我正在尝试在 ggplot2 中重新创建一个填充的等高线图,但是创建的多边形导致一些丑陋的剪裁:
考虑示例数据:
require(ggplot2)
require(MASS)
x <- runif(10000)
y <- rnorm(10000)
dt <- data.frame(x=x, y=y)
使用filled.contour
,我可以使用
得到密度图
k <- kde2d(x,y)
filled.contour(k,xlim=c(0,1), ylim=c(-3,3))
但是,使用 ggplot,密度多边形在它们与密度估计的某些边界相交的地方被切割。
p <- ggplot(dt, aes(x=x, y=y))
dens <- stat_density2d(aes(fill=..level..), geom="polygon")
p + dens
解决方案
user20650的评论确实解决了问题,好像runif对[0,1]有支持,但是核密度估计有点超出:
这是他的解决方案以供将来参考:
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)))
user20650的评论确实解决了这个问题,好像runif对[0,1]有支持,但是内核密度估计有点超出:
这是他的解决方案,所以我可以关闭问题。
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)))
bpeter 和 user20650 解决了这个问题,但他们的回答可能会产生另一个问题。在某些图上,扩展 x,y 限制会使图缩小到无法使用。
添加以下行应该可以解决问题(具有适当的 x,y 值):
coord_cartesian(ylim=c(-2, 2),xlim=c(0, 1))
我正在尝试在 ggplot2 中重新创建一个填充的等高线图,但是创建的多边形导致一些丑陋的剪裁:
考虑示例数据:
require(ggplot2)
require(MASS)
x <- runif(10000)
y <- rnorm(10000)
dt <- data.frame(x=x, y=y)
使用filled.contour
,我可以使用
k <- kde2d(x,y)
filled.contour(k,xlim=c(0,1), ylim=c(-3,3))
但是,使用 ggplot,密度多边形在它们与密度估计的某些边界相交的地方被切割。
p <- ggplot(dt, aes(x=x, y=y))
dens <- stat_density2d(aes(fill=..level..), geom="polygon")
p + dens
解决方案
user20650的评论确实解决了问题,好像runif对[0,1]有支持,但是核密度估计有点超出:
这是他的解决方案以供将来参考:
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)))
user20650的评论确实解决了这个问题,好像runif对[0,1]有支持,但是内核密度估计有点超出:
这是他的解决方案,所以我可以关闭问题。
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)))
bpeter 和 user20650 解决了这个问题,但他们的回答可能会产生另一个问题。在某些图上,扩展 x,y 限制会使图缩小到无法使用。
添加以下行应该可以解决问题(具有适当的 x,y 值):
coord_cartesian(ylim=c(-2, 2),xlim=c(0, 1))