Skip to content

Instantly share code, notes, and snippets.

@tgs
Created March 23, 2011 20:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tgs/883933 to your computer and use it in GitHub Desktop.
Save tgs/883933 to your computer and use it in GitHub Desktop.
Make a 2d or 3d histogram to visualize data density
% Code from http://goo.gl/lhXpN (Doug Hull's mathworks blog)
% With changes suggested by Andrea and Thomas in the comment thread
%
% See also "cloudplot":
% http://www.mathworks.com/matlabcentral/fileexchange/23238-cloudplot
% put your input data as vertical arrays in x and y
x = randn(100000,1);
y = randn(100000,1) * 20;
% Number of bins
n = 49;
xi = linspace(min(x(:)), max(x(:)), n);
yi = linspace(min(y(:)), max(y(:)), n);
xr = interp1(xi, 0.5:numel(xi)-0.5, x, 'nearest');
yr = interp1(yi, 0.5:numel(yi)-0.5, y, 'nearest');
% [yr xr]: Y then X because the plotting commands take matrices that look
% like Z(y-coord, x-coord)
Z = accumarray([yr xr] + 0.5, 1, [n n]);
figure(1);
surf(xi, yi, Z);
xlabel('x');
ylabel('y');
zlabel('count');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment