Nils Mackay
Nils Mackay

Reputation: 429

R, ggplot - Density plot shows gaps

I've been encountering some sort of bug when trying to plot a 2d density plot using ggplot2's function stat_density2d. When I only try to plot the outlines for the graph it seems to work fine:

ggplot(mydata, aes(x=x_loc, y=y_loc)) + stat_density2d(aes(fill = ..level..))

However when I try to fill in the layers using geom = "polygon"

ggplot(mydata, aes(x=x_loc, y=y_loc))+stat_density2d(aes(fill = ..level..), geom = "polygon")

I get this:

Filled in

This looks like it is giving geometry errors for some reason, but I'm not sure why. I've tried to work around this but I can't seem to find a solution. I've updated my R version and all my packages but it doesn't fix it.

As a reproducible example:

matrix = matrix(c(1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,1,2,3,1,2,3,1,2,3,1,2,
3,1,2,3,1,2,3,18,12,20,24,22,35,18,12,19,20,5,16,11,7,10,5,1,3), nrow = 18)

ggplot(as.data.frame(matrix), aes(x=V1, y=V2)) + 
stat_density2d(aes(fill = ..level..), geom = "polygon")

Which has the similar problems, for instance on the sides and on the top and bottom:

Example output

If anybody could help me with this that would be great, have stuck at this for several hours now.

Thanks in advance!

Upvotes: 1

Views: 619

Answers (1)

user2728808
user2728808

Reputation: 580

As mentioned in @joran's comment, this question seems to be of a similar ilk. The default clipping values seem to be causing the problem. The following works for me:

library(ggplot2)

matrix = matrix(c(1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,1,2,3,1,2,3,1,2,3,1,2,
3,1,2,3,1,2,3,18,12,20,24,22,35,18,12,19,20,5,16,11,7,10,5,1,3), nrow = 18)

ggplot(as.data.frame(matrix), aes(x=V1, y=V2)) + 
stat_density2d(aes(fill = ..level..), geom = "polygon")+ 
lims(x = c(-1,8),y = c(-.25,4.25))

Upvotes: 1

Related Questions