0

I have a simple, grouped bar plot. I'm trying to plot the error bars, too, but I can't seem to figure it out.

I'm not too great with for loops, but I don't know if that's the only solution to this, or if I can just add another line of code to plot the error bars.

Here's my code and graph:

% Plot raw data
y = [316.45 292.14 319.96; 305.59 287.99 295.21]  % first 3 #s are pre-test, second 3 #s are post-test
err = [13.12 5.67 12.36; 12.43 6.83 11.67]

box on

bar(y)
set(gca,'xticklabel',{'Pre-test'; 'Post-test'}) 
ylim([200 360])
ylabel('RT (ms)')
xlabel('Session')

enter image description here

CogNeuro123
  • 33
  • 1
  • 6
  • Possible duplicate of [How to plot a grouped bar chart with errors bar as shown in the figure?](https://stackoverflow.com/q/14256383/8239061) (MATLAB) – SecretAgentMan Dec 09 '19 at 21:38

1 Answers1

2

Here is a solution using the standard errorbar and bar functions. bar plots each group at the same x position, and uses the Xoffset property to shift the bars in a group. You can use the x position and Xoffset to plot the errorbars.

% Data
y = [316.45 292.14 319.96; 305.59 287.99 295.21]  % first 3 #s are pre-test, second 3 #s are post-test
err = [13.12 5.67 12.36; 12.43 6.83 11.67]

% Plot
figure(1); clf; 
hb = bar(y); % get the bar handles
hold on;
for k = 1:size(y,2)
    % get x positions per group
    xpos = hb(k).XData + hb(k).XOffset;
    % draw errorbar
    errorbar(xpos, y(:,k), err(:,k), 'LineStyle', 'none', ... 
        'Color', 'k', 'LineWidth', 1);
end

% Set Axis properties
set(gca,'xticklabel',{'Pre-test'; 'Post-test'});
ylim([200 360])
ylabel('RT (ms)')
xlabel('Session')

enter image description here

rinkert
  • 6,593
  • 2
  • 12
  • 31
  • 1
    Thank you very much! This is a simple enough for loop I can understand, I appreciate it – CogNeuro123 Dec 09 '19 at 22:03
  • In R2019b and later, use [XEndpoints](https://www.mathworks.com/help/matlab/ref/matlab.graphics.chart.primitive.bar-properties.html#mw_3d0c5b61-b082-4c79-b9c6-a21152ae26ff) – X Zhang Jul 12 '23 at 13:50