Reputation: 465
I am trying to plot 5 histograms in one plot. To make this readable, I have thought of using a 'cumulative' (not sure whether this is the right term) bar chart, but couldn't find an easy implementation in MATLAB. Is there one ?
Here is an example of what I am talking about:
a=1:5
b=5:-1:1
when I try a normal bar chart, it would look like this:
bar([a ;b]')
and what I want is this (excuse hasty image editing):
I cannot achieve this with using 'bar' twice with 'hold on', since one of the bar charts will cover the other one.
ps: if there are better ways of plotting multiple histograms on the plot, except using density curves, please feel free to advise :)
Upvotes: 3
Views: 1472
Reputation: 650
I believe you might be looking for :
bar([a ;b]', 'stacked')
=== EDIT 1 ===
Looking more closely at your drawing, you might also be looking for a less conventional "stacking" which you can achieve by superimposing both bars like so :
a=(1:5)';
b=(5:-1:1)';
c = a;
c(b<=a)=nan;
figure;
subplot(1,2,1);
bar([a,b]);
subplot(1,2,2);
hold on;
bar(a,'b');
bar(b,'r');
bar(c,'b');
hold off
This yields the following figure, which is similar to yours:
=== END OF EDIT 1 ===
=== EDIT 2 ===
here is an implementation of what i was suggesting in my comments to extend that idea to an arbitrary number of series. basically, each layer (from tallest to smallest) is painted (using patch) in a loop. Although this is not a Matlab Bar chart anymore (which, to my knowledge, cannot solve your problem due to the fact that independent horizontal bars for a given serie cannot be accessed through uistack), the resulting figure fits the description you gave.
function testBarOverlay()
% data initialization
nbSeries = 8;
nbBars = 5;
xt = 1:nbBars;
data = rand( nbBars, nbSeries );
%draw (then erase) figure and get the characteristics of Matlab bars (axis, colors...)
figure;
h = bar( data( :, 1 ) );
width = get( h, 'barWidth' );
delete( h );
% sort in order to start painting the tallest bars
[ sdata, idx ] = sort( data, 2 );
% get the vertices of the different "bars", drawn as polygons
x = [ kron( xt, [1;1] ) - width / 2; kron( xt, [1;1] ) + width / 2 ];
% paint each layer, starting with the 'tallest' ones first
for i = nbSeries : -1 : 1
y = [ zeros( nbBars, 1 ), sdata( :, i ), sdata( :, i ), zeros( nbBars, 1 ) ]';
p = patch( x, y, 'b' );
set( p, 'FaceColor', 'Flat', 'CData', idx( :, i )' );
end
end
=== END OF EDIT 2 ===
Upvotes: 4