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

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.

enter image description here

Anyone who knows what the reason could be, and how to solve it? Thanks a lot!

Community
  • 1
  • 1
Dendrobates
  • 3,294
  • 6
  • 37
  • 56

1 Answers1

4

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

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.

joran
  • 169,992
  • 32
  • 429
  • 468