问题
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.
Anyone who knows what the reason could be, and how to solve it? Thanks a lot!
回答1:
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.
来源:https://stackoverflow.com/questions/36456535/ggplot2-stat-density2d-produces-strange-triangles