How to draw contours over a bi-variate Gaussian so that the lines enclose a certain percentage of the distribution?
36 views (last 30 days)
Show older comments
I use fitgmdist to get the Gaussian distribution. Then I draw a contour plot of the distribution using fcontour . The problem is that I don't understand at what interval these lines are drawn. I would like the lines to be drawn such that for example 68% of the samples are within the first line, 95% are within the second line and so on.
What I have now looks like this:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/168853/image.png)
What I want is something similar to this:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/168855/image.jpeg)
so that I know which percentage of the distribution the lines are enclosing.
Any help is greatly appreciated.
0 Comments
Answers (1)
James Herman
on 27 Mar 2018
Probably no longer in need of a response but...
The way I solved this was to find the "levels" that the contours need to be drawn at to contain a certain percentile of the 2D gaussian. Given "alpha" (%), this depends on critical values of the chi-square distribution, for which you can use "chi2inv". More info here.
Below an example of how to calculate the "levels" for a couple alphas. It's done by using a purely diagonal covariance matrix ("unrotated"). After obtaining "pdlevels" you can feed those to contour...
mu = [7, 3];
cov = [1 0.2; 0.2, 1];
alpha = [0.2 0.7];
nAlpha = length(alpha);
% walk out from the mean to points such that all points closer
% comprise the central alpha% of the distribution; choose the
% direction along which this distance is shortest so that we
% can return the radius
pdpoints = repmat(mu, 2*nAlpha,1) + ...
repmat(sqrt(chi2inv(alpha, 2))*...
sqrt(cov),2,1).*sortrows(repmat(eye(2), nAlpha,1));
% calculate the value of the (unrotated) gaussian there.
pdlevels = mvnpdf(pdpoints(1:nAlpha,:), mu, diag(diag(cov)));
See Also
Categories
Find more on Contour Plots in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!