MATLAB Answers

error bars on grouped barplot with 2 axis

5 views (last 30 days)
forgood2
forgood2 on 26 Jul 2021
Edited: dpb on 26 Jul 2021
Hello, I have the following barplot:
clear all
clc
close all
(Separated off the brute force clear/close so folks can download w/o fear of wiping their own workspace -- dpb)
set(groot,'defaultAxesTickLabelInterpreter','latex');
set(groot,'defaulttextinterpreter','latex');
set(groot,'defaultLegendInterpreter','latex');
a = [37.6 0; 29.9 0];
b = [0 1.4 ; 0 1.1 ];
a(:,2)=zeros;
b(:,1)=zeros;
yyaxis left;
bar(1:2,a);
ylim([0 40]);
yyaxis right;
bar(1:2,b);
ylim([0 2]);
set(gca,'XTickLabel',{'part 1';'part 2';'part 1';'part 2'})
yyaxis left
ylabel('time/s')
yyaxis right
ylabel('mean/mm')
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
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;
hB=bar(x,a);
ylim([0 40]);ylabel('time/s')
hold on
hEB=errorbar(hB(1).XEndPoints,hB(1).YEndPoints,hB(1).YEndPoints/50,'LineStyle','none');
yyaxis right;
hB=[hB;bar(x,b)];
ylim([0 2]);ylabel('mean/mm');ytickformat('%.1f')
hold on
hEB(2)=errorbar(hB(4).XEndPoints,hB(4).YEndPoints,hB(4).YEndPoints/50,'LineStyle','none');
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'});
hB=bar(x,a);
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!