I think you want a 2D density estimate, which is implemented by kde2d
in the MASS
package.
df <- data.frame(x=rnorm(10000),y=rnorm(10000))
via MASS
and base R:
k <- with(df,MASS:::kde2d(x,y))
filled.contour(k)
via ggplot
(geom_density2d()
calls kde2d()
)
library(ggplot2)
ggplot(df,aes(x=x,y=y))+geom_density2d()
I find filled.contour
more attractive, but it's a big pain to work with if you want to modify anything because it uses layout
and takes over the page layout. Building on Brian Diggs's answer, which fills in colours between the contours: here's the equivalent with different alpha levels, with transparent points added for comparison.
ggplot(df,aes(x=x,y=y))+
stat_density2d(aes(alpha=..level..), geom="polygon") +
scale_alpha_continuous(limits=c(0,0.2),breaks=seq(0,0.2,by=0.025))+
geom_point(colour="red",alpha=0.02)+
theme_bw()
