MATLAB: Troubles assigning colorbar values in a bivariate histogram plot

bivariate histogramcolorbarscatter

Hello!
Im working with data of height and period of ocean waves, each pair have a power value associated, I have to get a bivariate histogram but instead of number of observations in colorbar i want that the scale represents the power associated.
I attached an example of the plots that i already have and the code to obtain it.
Xedges = [1:0.25:16];
Yedges = [0.00:0.025:1.6];
h = histogram2(Tp,Hs,Xedges,Yedges)
h.FaceColor = 'flat';
h.DisplayStyle = 'tile';
c=colorbar;
c.Label.String = 'NĂºmero de observaciones';
c.Label.FontSize = 14;
view(2)
I am new in matlab and maybe Im wrong with the function that i am using, i also tried with sccater3 but i have to group my data in bins
so this option doesnt work.
Thanks in advance for your help

Best Answer

Binned approach
The problems with using the binned bivariate histogram are
  1. The colors on the histrogram will be based on density rather than the power values.
  2. There are often more than 1 power value within each bin.
A solution to problem 1 is to use imagesc() instead.
A solution to problem 1 is to average the power values within each bin. Note that you're losing information here since the powers are averaged and the actual (x,y) coordinates of the data are binned. The scatter plot version does not have these losses.
Here's a demo using your data; you can add the contour from my other answer.
d = readmatrix('Dzi.txt');
Hs = d(:,1);
Tp = d(:,2);
power = d(:,3);
Xedges = [1:0.25:16]; % defined by OP

Yedges = [0.00:0.025:1.6]; % defined by OP
% determine which bin each Tp and Hs value is in
TpBins = discretize(Tp,Xedges);
HsBins = discretize(Hs,Yedges);
% group the Power values by bin
xyGroups = [TpBins(:),HsBins(:)];
[xyGroupUnq, ~, unqGroupID] = unique(xyGroups,'rows');
% average power values within groups
powerGroupMean = splitapply(@mean, power, unqGroupID);
% Reorganize power into matrix
powerMat = zeros(numel(Yedges)-1, numel(Xedges)-1);
idx = sub2ind(size(powerMat),xyGroupUnq(:,2),xyGroupUnq(:,1));
powerMat(idx) = powerGroupMean;
% Plot it
imagesc(Xedges, Yedges, powerMat)
set(gca,'YDir','normal')
cmap = jet(100);
cmap(1,:) = 1; % to make background white
colormap(cmap)
colorbar()
200108 111749-Figure 1.png