MATLAB Answers

error bars on grouped barplot with 2 axis

5 views (last 30 days)
forgood2 on 26 Jul 2021
Edited: dpb on 26 Jul 2021
Hello, I have the following barplot:
clear all
close all
(Separated off the brute force clear/close so folks can download w/o fear of wiping their own workspace -- dpb)
a = [37.6 0; 29.9 0];
b = [0 1.4 ; 0 1.1 ];
yyaxis left;
ylim([0 40]);
yyaxis right;
ylim([0 2]);
set(gca,'XTickLabel',{'part 1';'part 2';'part 1';'part 2'})
yyaxis left
yyaxis right
I want to add errorbars for the blue bars belonging to the left axis and the same for the orange bars belonging to the right axis.

Accepted Answer

dpb on 26 Jul 2021
Edited: dpb on 26 Jul 2021
Little tricky -- although in a recent release TMW finally made the XEndPoints property visible so at least can see it is there...although need to have a klew about how the grouped bar is drawn to be able to understand what really need -- and the documentation isn't at all good in that regards. The only example is a trivial one of a regular simple one-series bar plot. My (long-running) ranting about the shortcomings of bar() aside,
yyaxis left;
ylim([0 40]);ylabel('time/s')
hold on
yyaxis right;
ylim([0 2]);ylabel('mean/mm');ytickformat('%.1f')
hold on
xticklabels({'part 1','part 2'});
I arbitrarily used 1/50th the bar height for the error magnitudes; obviously you'll use your own values in lieu thereof.
NB: bar() creates two handles here (one for each group) with each call so the first handle you want is the first for the LH group data and then the last for the RH group with the "real" data values.
You could, of course, use the a(:,1), b(:,2) values, but this shows how to save/retrieve data from the bar chart itself for the generic solution.
If it weren't for the need to put the errorbar on,
x=categorical({'part 1','part 2'});
would get the xticklabels automagically, but then the x axes is a categorical axis and can't plot the explicit x positions for the errorbar -- they get rounded to the midpoint categorical tick location instead.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!