rggplot2

How to draw the outermost line using scatter plot and geom density line?


I want to draw the density line on the scatter plot using ggplot2.
Referencing this code, I draw the example figure below:

set.seed(1)
df <- data.frame(x = rnorm(200), y = rnorm(200))

ggplot(df, aes(x = x, y = y)) +
  geom_point() + 
  geom_density_2d()

enter image description here

The expected result is here. enter image description here


Solution

  • You can use a custom "break" to add contours of the density outside the range of the data. I arbitrarily chose a contour value of 0.005 based on the reciprocal of the number of points - I've highlighted it red for contrast.

    ggplot(df, aes(x = x, y = y)) +
      geom_point() + 
      geom_density_2d() +
      geom_density_2d(breaks=c(0.005), col="red")
    

    Output plot