MATLAB Answers


How can I make two axes on a clustered stack bar chart?

Asked by Renee
on 20 Nov 2012

I have made a clustered stack bar chart using Plot Groups of Stacked Bars by Evan on file exchange:

My data is in a 25x3x2 matrix. I currently have labels for the clusters (the 25 categories), and have used

legend('With', 'Without');

to label the two variables within each bar.

I am missing labels for the individual bars (the 3 bars per cluster). Is there a way to have x labels for both the individual bars and the cluster, like the "A cluster-of-stacked-bars graph" shown on the webpage



No products are associated with this question.

1 Answer

Answer by Jonathan Epperl
on 20 Nov 2012
 Accepted answer

Here is simple tweak to plotBarStackGroups.m that will allow you to label every single bar from left to right.

Just before the for loop, insert

xtick = [];    

Just before the end of the for loop, insert

xtick = [xtick; groupDrawPos(:)];

And then, after the hold off insert

xts = sort(xtick);

and delete what else is there.

Now you should be able to call it as before, but now the second parameter needs to be a cell array with a string containing the label of every bar, from left to right. Nice feature though: If there are less elements in the cell array than bars, then Matlab cycles through. Example:

 D=rand(25,3,2); % Make some Data
 C = mat2cell(char(randi(25,[25*3 1])+65),ones(25*3,1)); % and some labels
 plotBarStackGroups(D,C); % plot with a label for every bar
 plotBarStackGroups(D,C(1:3)); % that happens if you supply only 3 labels

You'll note that I used single-character labels. As soon as they get bigger it'll get very messy. And unfortunately, there is no easy way to rotate TickLabels in Matlab, you'll have to resort to the FEX there.

Also, there are now no more group labels, since those are only going to be less, you can maybe fix them there using text().

A third option would be to leave plotBarStackGroups as is and instead add labels on top of each bar, again using text. If you feel you need to do that let us know here, I'll try and help you with it.

  1 Comment

on 21 Nov 2012

Thank you! It works great. For the group labels, I added a second axis instead, which almost gives what I want.

position = get(axis1,'Position');
position(2) = position(2)-0.03;
position(4) = position(2)-0.0000001;
axis4 = axes('Position',position,...
  'TickLength',[0 0],...
  'YTick', [],...
  'XColor', 'k',...
xlabel('Minutes','FontSize', 18)
axis([0 26.5 0 1]);
xtick2=[-xtick(1)+0.5*[delt delt(end)]+xtick(1:end)];
  'TickLength',[0.01 0],...
  'YTick', []);
axis([0 26.5 0 1]);

Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

MATLAB Academy

New to MATLAB?

Learn MATLAB today!