问题描述
我正在尝试使用ggplot2
和stat_density2d
在R中构造密度热图.虽然它确实为我提供了2个轴上的密度图,但它在预期的热图旁边生成了奇怪的三角形空间.
I'm trying to construct a density heatmap in R, using ggplot2
and stat_density2d
. While it does give me a density plot over 2 axes, it produces strange triangular spaces next to the expected heatmap.
我正在关注,因此以下代码本身会生成热图(无散点图):
I'm following this example, hence the following code produces the heatmap itself (without scatter):
dfFilter <- data.frame(matrix(runif(2000, 0.0, 1.0),nrow=1000))
# HEATMAP
ggplot(dfFilter,aes(x= X1,y= X2))+
stat_density2d(aes(alpha=..level..), geom="polygon")
我的结果看起来与预期的相当,但是有一些意想不到的问题.看起来R正在连接点,但突然跳到情节的另一端继续.
My result looks quite as expected, but has some unexpected traingles. It looks like R is connecting dots, but suddenly jumps to the other side of the plot to continue.
谁知道原因可能是什么,以及如何解决这个问题?非常感谢!
Anyone who knows what the reason could be, and how to solve it? Thanks a lot!
推荐答案
我认为,这仅仅是多边形被裁剪以适合原始数据范围的结果.试试:
I believe this is simply a result of the polygons being clipped to fit into the original data range. Try:
ggplot(dfFilter,aes(x=X1,y=X2))+
stat_density2d(aes(alpha=..level..),geom = "polygon") +
lims(x = c(-0.2,1.2),y = c(-0.2,1.2))
尤其是如果您尝试在没有geom = "polygon"
且没有设置限制的情况下进行尝试,则会看到轮廓线修剪的差异. ggplot尝试绘制多边形时,如果等高线已被裁剪,则可以说它不知道如何完成该圆,因此它会跳来跳去.
In particular, if you try that without geom = "polygon"
with and without setting the limits, you'll see the difference in the clipping of the contour lines. When ggplot tries to draw the polygons, if the contour lines have been clipped it doesn't know how to complete the circle, so to speak, so it jumps around.
这篇关于ggplot2 stat_density2d产生奇怪的三角形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!