[Math] Plotting joint distribution of 2-D random variable

graphing-functionsMATLABprobabilityprobability distributions

I have some data which is basically a list of order pair (X,Y) and I want to see the joint distribution of this 2-D random variable. Is there any tool that provide this facility. Does Matlab has this kind of feature. I am able to plot distribution of 1D random variable only in Matlab and couldn't find the same for 2D. Yes it will be a 3D kind of plot.

Best Answer

I typically use something like this

[X, Y] = ndgrid(-10:10, -10:10);

pdfVals = zeros(size(X));
pdfFunc = @(x,y) ... % function to evaluate the pdf
for i=1:size(X,1)
    for j=1:size(X,2)
        pdfVals(i,j) = pdfFunc(i,j);
    end
end

figure(1); clf
contour(X, Y, pdfVals);

[edit] I may have misunderstood what you have available. Given just experimental data you can show an approximate pdf with the histogram tool.

% Generate random data
nData = 1e5;
data = zeros(2,nData);
m1 = 0; m2 = 1;
s1 = 1; s2 = 2;
for i=1:nData
    d1 = m1+s1*randn;
    d2 = m2+s2*randn;
    data(:,i) = [d1; d2];
end

% hist3 will bin the data
xi = linspace(min(data(1,:)), max(data(1,:)), 50);
yi = linspace(min(data(2,:)), max(data(2,:)), 50);
hst = hist3(data',{xi yi});

% normalize the histogram data
dx = xi(2)-xi(1);
dy = yi(2)-yi(1);
area = dx*dy;
pdfData = hst/sum(sum(hst))/area;

% plot pdf
figure(2); clf
contour(xi,yi,pdfData);