How to create a weighted 2D histogram

Viewed 787

A weighted 1D histogram seems pretty straight-forward. How can I implement a 2D weighted histogram given a weights-vector, w?

MATLAB:

x = randn(4,1);            //some random x input
y = randn(4,1);            //some random y input
w = [10, 20, 30, 40];      //weight to be assigned to corresponding data point in the generated histogram, i.e. the pixel intensity value

figure;
H = histogram2(x,y);   //Matlab built-in 2D histogram 

How should I use w in the above code snippet to get a weighted 2D histogram function.

*MATLAB code is preferred, but may also accept Python.

1 Answers

I'm sharing my weighted 2d histogram I took from some old code of mine...

function f  = hist2dw(x,y,weights,xedges,yedges)
%all inputs should be vectors
[~,xbin] = histc(x,xedges);
[~,ybin] = histc(y,yedges);

xbin(xbin==0) = inf;
ybin(ybin==0) = inf;
xnbin = numel(xedges);
ynbin = numel(yedges);

xy = xbin * ynbin + ybin;

[xyu,id] = unique(xy);
xyu(end) = []; % remove Inf bin
id(end) = [];
hstres = histc(xy,xyu);
hstres = hstres.*weights(id); % add the weights to the histogram
f(ynbin,xnbin)=0; % preallocate memory
f(xyu-ynbin) = hstres;

and here's an example on how to use it:

x = rand(1000,1);
y = rand(1000,1);
w=[ones(900,1) ; 5*ones(100,1) ];
edg=0:0.01:1;

imagesc(edg,edg,hist2dw(x(:),y(:),w(:),edg,edg));colorbar

enter image description here

Related