# [R] confidence bounds using contour plot

Pascal Hänggi pascal.haenggi at hydrologie.unibe.ch
Wed Jun 25 17:38:21 CEST 2008

```Hello

I'm trying to calculate 2d confindence bounds into a scatterplot using the
function "kde2d" (package MASS) and a contour plot.

I found a similar post providing a solution - unfortunatly I do not realy
understand which data I have to use to calculated the named "quantile":

Post URL: http://tolstoy.newcastle.edu.au/R/help/03b/5384.html

> (...)
>
>> Is there a way to plot a contour (empirical?) containing, say, 95% of the
>> values.
>
>Yes. You need a 2D density estimate (e.g. kde2d in MASS) then compute the
>density values at the points and draw the contour of the density which
>includes 95% of the points (at a level computed from the sorted values via
>quantile()).
>
>--
>Brian D. Ripley
>(...)

--
Example:

x <- rnorm(1000, mean = 0, sd = 1)
y <- rnorm(1000, mean = 1, sd = 1.3)
kerneld <- kde2d(x, y, n = 200, lims = c(-1.0, 1.0, 0.0, 2.0))

confidencebound <- quantile(kerneld\$z, probs= 0.95)

plot(x, y, pch=19, cex=0.5)
contour(kerneld, levels = confidencebound, col="red", add = TRUE)
--

How can I calculate the right contour containing 95% of the values?

Pascal

R 2.7.0, Win XP

--
Pascal Hänggi

Universität Bern
Geographisches Institut, Gruppe für Hydrologie
Hallerstrasse 12
CH-3012 Bern

+41 (0)31 631 54 71
pascal.haenggi at hydrologie.unibe.ch
http://www.hydrologie.unibe.ch
--

```