Skip to content

Instantly share code, notes, and snippets.

@CnrLwlss
Created August 3, 2021 15:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CnrLwlss/eda2e17809454eea497cea8c548d9590 to your computer and use it in GitHub Desktop.
Save CnrLwlss/eda2e17809454eea497cea8c548d9590 to your computer and use it in GitHub Desktop.
Contour plot where levels include quantiles instead of levels of constant density
library(MASS)
xdat = rnorm(1000)
ydat = rnorm(1000)
# https://stackoverflow.com/questions/16225530/contours-of-percentiles-on-level-plot
dens = kde2d(xdat, ydat, n=200); ## estimate the z counts
prob = c(0.95, 0.5)
dx = diff(dens$x[1:2])
dy = diff(dens$y[1:2])
sz = sort(dens$z)
c1 = cumsum(sz) * dx * dy
levs = sapply(prob, function(x) {
approx(c1, sz, xout = 1 - x)$y
})
plot(xdat,ydat, pch=19, col="red", cex.lab=2,cex.main=1.0,cex.axis=1.75)
contour(dens, levels=levs, labels=prob, add=T,lwd=2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment