Remove gaps in a stat_density2d ggplot chart without modifying XY limits

后端 未结 1 1133
执念已碎
执念已碎 2021-01-23 06:14

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


        
相关标签:
1条回答
  • 2021-01-23 06:35

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

    0 讨论(0)
提交回复
热议问题