Remove gaps in a stat_density2d ggplot chart witho

2019-07-18 16:33发布

问题:

When I run this code:

ggplot() + 
  stat_density2d(data = Unit_J, aes(x=X, y=Y, fill=..level.., alpha=0.9), lwd= 0.05, bins=50, col="blue", geom="polygon") +
  scale_fill_continuous(low="blue",high="darkblue") +
  scale_alpha(range=c(0, 0.03), guide="none") + 
  xlim(-6600,-3800) + ylim(400,2500) + 
  coord_fixed(expand=FALSE) + 
  geom_point(data = Unit_J, aes(x=X, y=Y), alpha=0.5, cex=0.4, col="darkblue") + 
  theme_bw() + 
  theme(legend.position="none")

I get this plot:

I know that increasing in this case X lims would solve the problem of unclosed lines shown on the left and right.

However, I want to keep these limits unchanged so that those "bugs" don't appear, and simply they must be beyond the limits, somehow hidden without creating those horrible lines.

Is there any possibility?

EDIT (download data here):

In order to ease and reproduce the example, you can download the data here

回答1:

The trick is to expand the canvas using xlim and ylim so that there is enough room for ggplot to draw complete contours around the data. Then you can use tighter xlim and ylim parameters within the coord_fixed term to show the window you want...

ggplot() + 
  stat_density2d(data = Unit_J, aes(x=X, y=Y, fill=..level.., alpha=0.9), 
                                lwd= 0.05, bins=50, col="blue", geom="polygon") +
  scale_fill_continuous(low="blue",high="darkblue") +
  scale_alpha(range=c(0, 0.03), guide="none") + 
  xlim(-7000,-3500) + ylim(400,2500) + #expanded in x direction
  coord_fixed(expand=FALSE,xlim=c(-6600,-3800),ylim=c(400,2500)) + #added parameters 
  geom_point(data = Unit_J, aes(x=X, y=Y), alpha=0.5, cex=0.4, col="darkblue") + 
  theme_bw() + 
  theme(legend.position="none")



标签: r ggplot2