Clear Filters
Clear Filters

Offsetting error bars on plot and showing both positive and negative values.

9 views (last 30 days)
Hi all,
I have a brief question.
Aside from manually editing the following graph in adobe illustrator or the likes, is there a way to have these error bars offset so they appear over only the orange bars. Moreover, is there a way that I can make the error bars two tailed.
Here is my code:
function GraphDataAbs( Title, Legend, YLabel, YValues_mean, YValues_std, Behaviours ) %Add back in YValues for scatter
xvalues= (1:numel(Behaviours));
hold on;
er = errorbar(xvalues, YValues_mean(1,:), YValues_std);
hold on;
bar(xvalues, YValues_mean, 'BarWidth', 1);
hold on;
er.Color = [0 0 0];
er.LineStyle = 'none';
ax = gca;
ax.XColor = 'k'
ax.YColor = 'k'
set(gca, 'FontName', 'Tahoma')
ylim([0, ((max(max(YValues_mean))*1.6))]);
ylabel (YLabel);
filename = Title
saveas(h,filename, 'epsc')

Accepted Answer

Tommy on 4 Jun 2020
If you plot the errorbars after you plot the bars, then they will show on top of the bars and you will be able to see the error in the negative y direction.
To shift the errorbars so that they lie on top of the dark orange bars only, you need to find the centers of those orange bars and pass those values into errorbar() in place of xvalues, which are the centers of the bar groups. If you have R2019b or later, you can use the bar property XEndPoints to find the centers of individual bars. See here for an example:
I am on R2019a, so I instead used the undocumented bar property XOffset, discussed here:
and here:
which left me with the following code:
% sample data
Behaviours = {'LabelA', 'LabelB', 'LabelC'};
YValues_mean = [80, 90; 100, 110; 60, 50];
YValues_std = [25, 37, 12];
xvalues= (1:numel(Behaviours));
hold on;
b = bar(xvalues, YValues_mean, 'BarWidth', 1);
drawnow % <- used to update the value of XOffset
er = errorbar(xvalues+b(1).XOffset, YValues_mean(:,1), YValues_std);
er.Color = [0 0 0];
er.LineStyle = 'none';

More Answers (0)

Community Treasure Hunt

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

Start Hunting!