How best to overlay bar graphs from histcounts of different data?
17 views (last 30 days)
Show older comments
I wish to overlay bar graphs from two different samples that use histcounts. The length of the separate counts are not equal nor neccessarily is their bin sizes. I am using the Freedman-Diaconis bin method to ensure the best bin sizing automatically. Ultiamtely I want to best visualize the different data by color and having all the bars of the same width--and importantly in an interlaced (or side by side) fashion. I am not sure if this is possible and cannot get around doing this. I should add, I am centering the bins between the bin edges for the data and adjusted the bars to have the same width. Here's an example:
figure;
[v1, e1] = histcounts([2 5 3.4 5.3 5 4 8 7],'BinMethod','fd');
de = diff(e1)/2; % difference btwn bins
wcl1 = e1(1:end-1) + de; % bin center location
b1 = bar(wcl1,v1,0.25);
hold on;
[v2, e2] = histcounts([3.4 5.5 6.4 6.9 7],'BinMethod','fd');
de = diff(e2)/2;
wcl2 = e2(1:end-1) + de;
b2 = bar(wcl2,v2,0.25);
hold off
As it turned out the centered bin locations are identical for both data set and this visualization gives the false impression any one bar are is highlighting a breakdown of composing parts. How best to deal with such a case? Can I get the bar function to have the blue and red bars of say at column 5 side by side? In centering between the bin edges, I believe this is the best approach but I am open to any suggestion for best visualizing. Thank you in advance for any help or suggestions.
0 Comments
Accepted Answer
Matt J
on 9 Jun 2023
A solution with interlacing:
[v1, e1] = histcounts([2 5 3.4 5.3 5 4 8 7],linspace(3,6,4));
[v2, e2] = histcounts([3.4 5.5 6.4 6.9 7],'BinMethod','fd');
fcn=@(z)conv(z,[1,1]/2,'valid');
e1=fcn(e1);
e2=fcn(e2);
E=unique([e1,e2]);
V1=interp1(e1,v1,E);
V2=interp1(e2,v2,E);
bar(E,[V1;V2])
xticks(E)
More Answers (2)
Matt J
on 9 Jun 2023
Edited: Matt J
on 9 Jun 2023
Maybe make the bars semi-transparent? You can also play with the edge thicknesses to emphasize the area of inclusivity of the bars.
[v1, e1] = histcounts([2 5 3.4 5.3 5 4 8 7],'BinMethod','fd');
[v2, e2] = histcounts([3.4 5.5 6.4 6.9 7],'BinMethod','fd');
fcn=@(z)conv(z,[1,1]/2,'valid');
b1 = bar(fcn(e1),v1,'w','FaceAlpha',0.5,'LineWidth',2,'EdgeColor','r'); hold on;
b2 = bar(fcn(e2),v2,'b','FaceAlpha',0.5,'EdgeColor','none'); hold off;
See Also
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!