Clear Filters
Clear Filters

Is there a way to use hist3 without the height of each bar indicating the number of elements in a bin?

4 views (last 30 days)
I'm trying to create a bivariate histogram plot, but I have a third z variable other than x and y. Since each x and y pair corresponds with a specific z value, I am trying to create a bivariate histogram plot whose height will not be the number of elements in that bin, but instead the cumulative z values in that bin. Is there any way to do this with hist3? If not, what else can I use?

Accepted Answer

Walter Roberson
Walter Roberson on 21 Aug 2023
discretize on the X and Y recording the indices in each case. Then
totals = accumarray([Yindices(:), Xindices(:)], Zvalues());
The result will be max(Yindices) by max(Xindices) of total Z, and you can then bar3() .
(In practice it would be a good idea to pass in the expected output size of the array as the third parameter.)
  6 Comments
Walter Roberson
Walter Roberson on 28 Aug 2023
Example with bins that are 15 degrees by 15 degrees.
rng(655321)
N = 100;
lats = rand(1, N) * 180 - 90;
lons = rand(1,N) * 360 - 180;
values = rand(1,N) * 50;
geoscatter(lats, lons)
latedges = -90:15:90;
lonedges = -180:15:180;
nlatbins = numel(latedges)-1;
nlonbins = numel(lonedges)-1;
latbin = discretize(lats, latedges);
lonbin = discretize(lons, lonedges);
bincounts = accumarray([latbin(:), lonbin(:)], 1, [nlatbins, nlonbins]);
imagesc(latedges, lonedges, bincounts); colorbar(); title('counts per bin'); set(gca, 'YDir', 'normal')
bintotals = accumarray([latbin(:), lonbin(:)], values(:), [nlatbins, nlonbins]);
imagesc(latedges, lonedges, bintotals); colorbar(); title('totals per bin'); set(gca, 'YDir', 'normal')
lats(1:5)
ans = 1×5
-33.4773 -20.4551 -56.6026 67.4535 51.1198
latbin(1:5)
ans = 1×5
4 5 3 11 10
latedges(1:6)
ans = 1×6
-90 -75 -60 -45 -30 -15
-33.4773 degrees is between -45 degrees and -30 degrees, so it falls into the 4th bin-- the bin that covers [-45, 30). Likewise, -20.4551 is in [-30, -15) which is the 5th bin so it gets index 5.
In the case of edges that are equidistant, you can calculate the indices in more efficient ways -- but not necessarily clearer ways than using discretize()

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!