Creating a heatmap to visualize denisity of 2D point data

60 views (last 30 days)
Hello,
I am trying to create a heat map from an Mx2 matrix of point data. The point data represents spatial locations and I am attempting to create a heat map that highlights densely-clustered points from sparsely-clustered points. the data is stored in a variable called points. points(:,1) is x data and points(:,2) is y data. when I type HeatMap(points) I get useless information. Is there a way I can visualize the density of these points in a heat map? I tried hist3, but it doesn't represent the data the way I would like.
Thanks,
Kyle

Accepted Answer

Walter Roberson
Walter Roberson on 19 Jun 2015
grid = 256; %refinement of map
minvals = min(points);
maxvals = max(points);
rangevals = maxvals - minvals;
xidx = 1 + round((points(:,1) - minvals(1)) ./ rangevals(1) * (grid-1));
yidx = 1 + round((points(:,2) - minvals(2)) ./ rangevals(2) * (grid-1));
density = accumarray([yidx, xidx], 1, [grid,grid]); %note y is rows, x is cols
imagesc(density, 'xdata', [minvals(1), maxvals(1)], 'ydata', [minvals(2), maxvals(2)]);
(This will make the image slightly larger than would be correct. It's probably not worth correcting for.)
  3 Comments
Kyle
Kyle on 23 Jun 2015
Got it! All I needed to do was this: set(gca,'YDir','normal') after your code. Thanks!
Cai Chin
Cai Chin on 15 Nov 2020
Hi, I am trying to do a very similar thing - I used your code but it only generates a blue frame instead of a colour density map. Instead of having a matrix input, I have 2 vectors 'v' and 'w' which I tried making into a matrix to fit your code.
I was wondering if you wouldn't mind please pointing out what the issue is or suggesting an alternative?
Thanks in advance.
% Convert vectors 'v' and 'w' into a matrix
points = [v, w];
% Generate colourmap of density
grid = 256; %refinement of map
minvals = min(points);
maxvals = max(points);
rangevals = maxvals - minvals;
xidx = 1 + round((points(1) - minvals(1)) ./ rangevals(1) * (grid-1));
yidx = 1 + round((points(2) - minvals(2)) ./ rangevals(2) * (grid-1));
density = accumarray([yidx, xidx], 1, [grid,grid]); %note y is rows, x is cols
imagesc(density, 'xdata', [minvals(1), maxvals(1)], 'ydata', [minvals(2), maxvals(2)]);
set(gca,'YDir','normal');

Sign in to comment.

More Answers (0)

Categories

Find more on Data Distribution 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!