error bars on grouped barplot with 2 axis

3 views (last 30 days)
forgood2
forgood2 on 26 Jul 2021
Edited: dpb on 26 Jul 2021
Hello, I have the following barplot:
clearall
clc
closeall
(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;
yyaxisleft;
bar(1:2,a);
ylim([0 40]);
yyaxisright;
bar(1:2,b);
ylim([0 2]);
set(gca,'XTickLabel',{'part 1';'part 2';'part 1';'part 2'})
yyaxisleft
ylabel('time/s')
yyaxisright
ylabel('mean/mm')
我想添加errorbars belongin蓝色酒吧g 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,
yyaxisleft;
hB=bar(x,a);
ylim([0 40]);ylabel('time/s')
holdon
hEB=errorbar(hB(1).XEndPoints,hB(1).YEndPoints,hB(1).YEndPoints/50,'LineStyle','none');
yyaxisright;
hB=[hB;bar(x,b)];
ylim([0 2]);ylabel('mean/mm');ytickformat('%.1f')
holdon
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)

s manbetx 845

Community Treasure Hunt

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

Start Hunting!