0

I have a scatterplot and I need to draw a contour that contains all (or almost all) points.

I have managed to do that with stat_density_2d() with the bins option set to 2 and the geom_polygon(). However, since I have to set the bin to 2, I still have 2 contours, one in the 'center' of the polygon and the outter one. I only need the outter one.

What I have (a polygon with 2 bins: an inner one and the outter one): scatterplot and contour with 2 bins

What I need: scatterplot and contour with only 1 outter bin

The inner bin looks small in this example but it looks unprofessional in bigger and more complex graphs.

Example:

set.seed(20)
x = rnorm(20, 3)
y = rnorm(20, 4)
points = tibble('x'=rnorm(10, 3), 'y'=rnorm(10, 4))
ggplot2::ggplot(data=points, mapping=aes(x=x, y=y, fill='grey', colour='black')) +
  geom_point() +
  stat_density_2d(aes(colour='black'), bins=2, geom='polygon') +
  scale_fill_identity() + scale_colour_identity() +
  geom_vline(xintercept=0, colour = 'black', linetype = 'solid') +
  geom_hline(yintercept=0, colour = 'black', linetype = 'solid') +
  xlim(-8, 8) + ylim(-8, 8)

Similar questions:

(the package in which this soution is based it is not longe availble)

ggplot: How to draw contour line for 2d scatter plot to outline the data points

How to plot a contour line showing where 95% of values fall within, in R and in ggplot2

  • This might not work for you, but setting colour = NA in geom_density_2d removes the lines, just leaving the shaded area – Richard Telford Sep 27 '18 at 12:18
  • Please check [this answer](https://stackoverflow.com/a/49072992/1286528). I would say that your approach is wrong. Instead of calculating density, plotting density and then removing density you just can encircle points using `ggalt::geom_encircle` – pogibas Sep 27 '18 at 12:23

0 Answers0