stacked histogram and xaxis issues
4 views (last 30 days)
Show older comments
Yasmin Samy
on 22 May 2018
Commented: Yasmin Samy
on 24 May 2018
Hello, I`m plotting histograms and would like stack 2 data sets instead of having them overlap. The problem is i didn`t find any options for histograms to do that in Matlab. It seems you need to use bar, but then i get the issue of the xaxis ticks and labels. Does anyone know how to properly plot stacked histograms?
For bar plots, how do we set the xaxis ticks and labels? (i tried set(gca....) and d.Xtick...and it didn`t work.
thanks
3 Comments
OCDER
on 23 May 2018
Is the stacked bar graph what you're looking for?
%Example from MathWorks website:
y = [2 2 3; 2 5 6; 2 8 9; 2 11 12];
bar(y,'stacked')
Accepted Answer
Benjamin Kraus
on 23 May 2018
In order to use the bar command to plot a histogram, you need to specify the X-values when you call the bar command. For example:
[N1,edges] = histcounts(randn(1000,1));
N2 = histcounts(randn(1000,1),edges); % Bin using the same edges
ctrs = (edges(1:end-1)+edges(2:end))/2; % Calculate the bin centers
bar(ctrs, [N1' N2'],1,'stacked','FaceAlpha',0.6);
Once that is done, you can either set the ticks to auto, or to the specific bin edges:
xticks auto % Use automatic ticks
xticks(edges) % Use specific edges
6 Comments
dpb
on 24 May 2018
Edited: dpb
on 24 May 2018
Indeed xticks was introduced in 16b
>> help bar
bar Bar graph.
...
bar(X,Y,WIDTH) or bar(Y,WIDTH) specifies the width of the bars. Values
of WIDTH > 1, produce overlapped bars. The default value is WIDTH=0.8
...
The doc version uses
...
bar(_____,width)
...
which leaves more to imagination, but the underscore implies the all previous explicit arguments prior to that; iow x,y
Show us what you got; explain specifically what isn't what you want and what that is...
ADDENDUM
Taking a guess, try
hAx=gca; % get handle
xlim([-4.5 4.5]) % symmetrize range
hAx.XAxis.TickLabelFormat='%0.1f'; % consistent format
hAx.XAxis.FontSize=9; % get a little more room
hAx.XTick=edges; % put ticks at bin edges
Probably still won't be sufficient room unless spread figure out wider to clearly read the tick values; you'll have to decide what's more important to show...
More Answers (0)
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!