R2014b Histogram of multiple data sets

6 views (last 30 days)
I'm trying to show histograms of four different vectors on a single set of axes and can't make it print them adjacent to one another, staggered, stacked, or anything other than right on top of each other.
code:
data1 = randn(20,1);
data2 = randn(30,1);
data3 = randn(40,1);
data4 = randn(50,1);
edges = -4:1:4;
histogram(data1,edges); hold on;
histogram(data2);
histogram(data3);
histogram(data4);
%Technically, I did these all with 'Normalization', 'probability' too to equalize height
Even with transparency it's impossible to tell what it shows. I tried grouping the four vectors into one array (with gap from different length vectors filled by NaN), but then the histogram function groups all the data together into a single chart. I'd like to show it so that for each bin (like 0-1), there are four bars in different colors side-by-side, ideally with a gap before the next block of four so it's clear which ones go together. Thanks.

Accepted Answer

the cyclist
the cyclist on 29 Sep 2015
Edited: the cyclist on 29 Sep 2015
One way is to use the histcounts command to get the counts, and then use the bar command to do the plotting (because it will do the side-by-side):
rng 'default'
data1 = randn(20,1);
data2 = randn(30,1);
data3 = randn(40,1);
data4 = randn(50,1);
edges = -4:1:4;
h1 = histcounts(data1,edges);
h2 = histcounts(data2,edges);
h3 = histcounts(data3,edges);
h4 = histcounts(data4,edges);
figure
bar(edges(1:end-1),[h1; h2; h3; h4]')
I did not take great care to properly line up the "edges" variable with the counts. There are some nuances with respect to exactly how the binning is done. I suggest reading the documentation for histcounts.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!