Search code examples
matlabmatlab-figure

How to overlay single data points on bar graph in MATLAB?


I am trying to plot a bar graph with means of 9 data points. I want to plot the bar graph with individual data points overlaid on the bar. Here is the code to generate the bar graph. I want to overlay each bar with the individual data points whose average is y. Any suggestions for how to do this would be helpful. Thank you!

x_num = [1:4];
x = categorical({'High PU-High RU','High PU-Low RU', 'Low PU-High RU', 'Low PU-Low RU'});
y = [0.557954545, 0.671394799, 0.543181818, 0.660227273];
figure
bar(x,y,0.4)
title('Economic Performance')
xlabel('Conditions')

Solution

  • You can just hold on and plot the additional points

    % Generate some data
    x = 1:4;
    y = rand(9,4);   % note: 4 columns, N rows
    ymean = mean(y); % mean of each column for bar
    
    figure();
    hold on; % plot multiple things without clearing the axes
    bar( x, ymean, 0.4 ); % bar of the means
    plot( x, y, 'ok' );   % scatter of the data. 'o' for marker, 'k' for black
    hold off
    

    There are loads of options for the plot styling, using 'o', 'x' or '.' as a marker type will make it a scatter rather than a line which is what you want here, other than that you can go crazy with sizing/color/linewidth etc, see the documentation.