无需修改XY限制即可消除stat_density2d ggplot图表中的间隙

ant*_*sor 2 r ggplot2

当我运行此代码时:

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")
Run Code Online (Sandbox Code Playgroud)

我得到这个情节: 在此处输入图片说明

我知道在这种情况下增加X lims可以解决左右两边显示的不闭合线条的问题。

但是,我想保持这些限制不变,以使这些“错误”不会出现,并且它们必须超出限制,以某种方式隐藏而不造成那些可怕的界限。

有没有可能?

编辑(在此处下载数据):

为了简化和重现示例,您可以在此处下载数据

And*_*tar 5

诀窍是使用xlim和扩展画布,ylim以便有足够的空间ggplot在数据周围绘制完整的轮廓。然后你可以使用更严格的xlimylim在中的参数coord_fixed项,以显示你想要的窗口...

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")
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明