2

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: enter image description here

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

antecessor
  • 2,688
  • 6
  • 29
  • 61
  • Use `coord_cartesian(xlim=c(-6600,-3300),ylim=(400,2500))` instead of using `xlim` and `ylim`. This will plot the whole thing and then just show a window, rather than clipping the data before plotting. – Andrew Gustar Apr 13 '18 at 09:37
  • It does not work @AndrewGustar – antecessor Apr 13 '18 at 10:11

1 Answers1

5

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

enter image description here

Andrew Gustar
  • 17,295
  • 1
  • 22
  • 32