Matt
Matt

Reputation: 23

Stop errorbars from overlapping in matlab

I have multiple sets of data with standard deviations I need to present - and I've been using error bars. When I plot multiple sets on the same plot, however, some of the error bars overlap.

Is there an easy way to make it such that the error bars for a certain tick value are slightly offset, such that it's clear they belong to that tick marker, but don't overlap so their spreads are clear? I have seen a similar question answered and performed with bar graphs, but am having a hard time extending it to errorbar.

Thanks!

Example image, with overlapping error bars: 1

Code used to produce image:

val1 = [818.23,819.12,820.73,821.93,819.21];
val2 = [840.04,839.77,841.20,842.54,841.50];
val1std = [14.81,5.17,14.08,20.24,11.95];
val2std = [14.81,5.17,14.08,20.24,11.95];

figure
set(gca,'fontsize',18)
hold on
errorbar(val1,val1std,'ok','linewidth',2,'MarkerSize',6','MarkerFaceColor','k')
errorbar(val2,val2std,'xk','linewidth',2,'MarkerSize',6','MarkerFaceColor','k')
xlabel('Some property (unit)','fontsize',18,'interpreter','latex')
ylabel('Another property (unit)','fontsize',18,'interpreter','latex')
set(gca,'XTickLabel',{'','0.10','0.08','0.06','0.04','0.02',''}) 
set(get(gca, 'yLabel'), 'Rotation',90);
set(gca,'TickLabelInterpreter','latex')
xlim([0 6])
ylim([800 900])
set(gca, ...
    'box', 'on',...
    'tickdir', 'in',...
    'ticklength',[.02 .02],...
    'linewidth',1,...
    'ygrid','off')
set(gcf,'paperpositionmode','auto','Color',[1,1,1])
h=legend({'data1','data2'})
set(h,'Interpreter','latex')

Upvotes: 2

Views: 1335

Answers (1)

Luis Mendo
Luis Mendo

Reputation: 112689

Specify the x input to errorbar and add a little offset manually. You can do it as follows. Modified lines are indicated with comments.

val1 = [818.23,819.12,820.73,821.93,819.21];
val2 = [840.04,839.77,841.20,842.54,841.50];
val1std = [14.81,5.17,14.08,20.24,11.95];
val2std = [14.81,5.17,14.08,20.24,11.95];

figure
set(gca,'fontsize',18)
hold on
delta = .07; % Adjust manually
errorbar((1:numel(val1))-delta, val1,val1std,'ok','linewidth',2,'MarkerSize',6',...
'MarkerFaceColor','k') % Add X input
errorbar((1:numel(val2))+delta,val2,val2std,'xk','linewidth',2,'MarkerSize',6',...
'MarkerFaceColor','k') % Add X input
xlabel('Some property (unit)','fontsize',18,'interpreter','latex')
ylabel('Another property (unit)','fontsize',18,'interpreter','latex')
set(gca,'XTickLabel',{'','0.10','0.08','0.06','0.04','0.02',''}) 
set(get(gca, 'yLabel'), 'Rotation',90);
set(gca,'TickLabelInterpreter','latex')
xlim([0 6])
ylim([800 900])
set(gca, ...
    'box', 'on',...
    'tickdir', 'in',...
    'ticklength',[.02 .02],...
    'linewidth',1,...
    'ygrid','off')
set(gcf,'paperpositionmode','auto','Color',[1,1,1])
h=legend({'data1','data2'})
set(h,'Interpreter','latex')

This gives the following figure.

enter image description here

Upvotes: 2

Related Questions