How to show bin counts' percentage values in Histogram2 tile plot?
Show older comments
Hi Dear Community
I have x and y values*, I want to plot it like a 3D Histogram but on the top view. (It should look like a heatmap with a colorbar).
I made the plot, but I want to show the values percentages or counts on the each rectangle. Here is the code below:
hFig = figure;
hAxes = axes(hFig);
xVals = randn(1,10000);
yVals = randn(1,10000)*5;
xEdges = min(xVals):1:max(xVals);
yEdges = min(yVals):5:max(yVals);
hHist = histogram2(hAxes,xVals,yVals,xEdges,yEdges,'DisplayStyle','tile');
colorbar;
This code only plots the tiled histogram. I looked the hHist object and saw that it has the BinCounts property which actually gives the number of points in each rectangle.
So I calculated percentages as follows:
percentagesMatrix = (hHist.BinCounts / sum(hHist.BinCounts,'all'))*100;
I don't know how to update the rectangles with this percentage values. I want all that matrix is written inside the boxes. And update the colorbar accordingly.
Any help will be appreciated.
Thank you so much! :)
*Note: x and y values normally comes from a tall table as a tall array.
Here is the sample plot below. I want to see numbers inside these squares:

Accepted Answer
More Answers (1)
Guillaume
on 4 Nov 2019
It's all explained in the doc of histogram2. You don't even have to make the percentage calculation yourself, histogram2 will do it for you if you specify 'Normalization', 'probability':
hHist = histogram2(hAxes,xVals,yVals,xEdges,yEdges,'DisplayStyle','tile', 'Normalization', 'probability');
5 Comments
Luna
on 5 Nov 2019
Shashank Bhatia
on 17 Nov 2019
Hve you solved it yet?
Luna
on 21 Nov 2019
Shashank Bhatia
on 22 Nov 2019
Thanks it works for me!!
Best Regards,
SHashank
Luna
on 27 Nov 2019
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!