我正在尝试在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)))
答案 0 :(得分:2)
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)))
答案 1 :(得分:1)
bpeter和user20650解决了这个问题,但他们的回答可能会产生另一个问题。在某些图表中,扩展x,y限制可以使图表也缩小为有用。
添加以下行应修复事物(使用适当的x,y值):
coord_cartesian(ylim=c(-2, 2),xlim=c(0, 1))