0
#FIG1
ggplot(mylayer2,  aes(x= Value, fill = Condition)) +
  geom_density(alpha = .5)+
  xlim(0.2,0.8)+
  ylim(0,4)

#FIG2
ggplot(mylayer2,  aes(x= Value, fill = Condition)) +
  geom_density(alpha = .5)

I am using ggplot in R to visualise two groups of data. However, there is a gap/cracking part in the density plot of condition 1(FIG1). When I remove xlim() and ylim() then there's no gap anymore(FIG2). Is there a way I could fix it?

FIG1

FIG2

#original data
structure(list(Value = c(0.4375, 0.28125, 0.65625, 0.46875, 0.4375, 
0.5625, 0.53125, 0.59375, 0.4375, 0.3125, 0.5, 0.4375, 0.53125, 
0.375, 0.5, 0.40625, 0.53125, 0.5625, 0.34375, 0.59375, 0.5, 
0.4375, 0.4375, 0.46875, 0.34375, 0.53125, 0.5625, 0.5625, 0.28125, 
0.46875, 0.625, 0.5, 0.4375, 0.375, 0.5, 0.25, 0.40625, 0.40625, 
0.3125, 0.46875, 0.5625, 0.375, 0.46875, 0.375, 0.375, 0.40625
), Condition = c("1", "1", "1", "1", "1", "1", "1", "1", "1", 
"1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", 
"1", "2", "2", "2", "2", "2", "2", "2", "2", "2", "2", "2", "2", 
"2", "2", "2", "2", "2", "2", "2", "2", "2", "2", "2")), row.names = c(NA, 
-46L), class = c("tbl_df", "tbl", "data.frame"))
  • With `xlim()` and `ylim()` your throwing out data which is outside these limits. In your example the data points with y > 4 are thrown out before plotting. Your probably want to use `coord_cartesian(xlim = c(0.2, 0.8), ylim = c(0,4))` instead. This allows you to "zoom" in on the data without creating the "gap". See here for more detailed explanations: [Limit ggplot2 axes without removing data (outside limits): zoom](https://stackoverflow.com/questions/25685185/limit-ggplot2-axes-without-removing-data-outside-limits-zoom) – AndreasM Nov 10 '20 at 09:34
  • AndreasM's suggestion is correct, but I'd like to also point out that you can set the out-of-bounds behaviour in the position scales. For example `scale_y_continuous(limits = c(0, 4), oob = scales::oob_keep)`. – teunbrand Nov 10 '20 at 10:41
  • Does this answer your question? [Limit ggplot2 axes without removing data (outside limits): zoom](https://stackoverflow.com/questions/25685185/limit-ggplot2-axes-without-removing-data-outside-limits-zoom) – Ian Campbell Nov 11 '20 at 02:02

0 Answers0