MATLAB: Different columns for the same X-axe in stacked bar figure

barMATLABstacked

Hi all,
Im wondering to plot a bar figure with 6*2=12 bars, coupled by pairs. As it is said, a picture is worth a thousand words, so I'll paste you my code and the results I get, and then I'll show you a figure treated to get the results I want.
First, the code:
h=figure();
bar(A,[X Y Z F G H],'stacked');
legend('X','Y','Z','F','G','H');
grid on;
xlabel('A');
ylabel('B');
where X, Y, Z, F, G, H and A are 6×1 arrays.
And the result are this:
However, the wondered result would look more like the image below. This figure has been done from the previous one.
I have tried to build a 3 dimensional matrix with cat(3,A,A) and cat(3,[X Y Z],[F G H]), but this is not accepted by bar. I have also tried to use hold on like:
h=figure();
bar(A,[X Y Z],'stacked');
hold on;
bar(A,[F G H],'stacked');
legend('X','Y','Z','F','G','H');
grid on;
xlabel('A');
ylabel('B');
But the results still not the wondered:
Anybody has any help?

Best Answer

bar is very difficult function in Matlab when you want anything they've not already canned for you, and while using 'grouped' and 'stacked' together doesn't error (at least here thru R2014b) it doesn't work as would like, either; it just takes the first option string it finds and ignores the other.
To get both effects, have to resort to subterfuge...first to find the x offset needed for a 'grouped' plot of same number of bars, then build the desired result as stacked in two overlaid bar plots, one for each group of three--
hBarGrp=bar(abs(randn(6,2)),'grouped','stacked'); % six bars, group by 2
off=hBarGrp(2).XOffset; % hidden property, offset from nominal x
hBar1=bar(x-off,y1,0.25,'stacked'); % draw first stacked as wanted
hold all % hold axes, don't reset color order position
hBar2=bar(x+off,[nan(size(y2)) y2],0.25,'stacked'); % second with place holder
xlim([0.5 6.5])
The tricks are twofold --
  1. Use the 'grouped' form with the number of groups and bars per group as the y value and retrieve the x-axes offset for the center of the bars from the nominal x value. This isn't made any easier by the fact TMW hid the property so there's no way to know it exists unless someone points it out or you go to great depths on on to uncover it, and;
  2. The second stacked plot uses an identically sized array of dummy placeholders in front of the actual second y data array to force color cycle to not start over again from 1 for the bars; it begins from first bar for each call so must have the second look as though are all twelve bars being drawn even though the NaN elements aren't shown.
The width parameter of 0.25 I fudged manually, couldn't figure out how to retrieve a useful value to compute it from the barplot itself, unfortunately.
The above results in the following where the two y arrays were abs(randn(6,3)) for right sized array per query.