Search code examples
matlabplotmatlab-figurelegenderrorbar

Group plots with error-bars


I have the following code that makes a plot:

dfs = [0  5 10 15 20 25 ];
Intensities = [0.0593 0.0910 0.1115 0.0611 0.0975 0.0715] ;
SE = [0.2165 0.2068 0.2555 0.2479 0.2340 0.2239];

errorbar(dfs, Intensities, SE, 'ro');
hold on
plot(dfs,Intensities,'bo');
title('\fontsize{14}Intensities per condition');
hold off;

ylim([-0.2 0.5])

names = {'\fontsize{12}Cond1, Group1'; '\fontsize{12}Cond2, Group1'; '\fontsize{12}Cond1, Group2'; '\fontsize{12}Cond2, Group2'; '\fontsize{12}Cond1, Group3';'\fontsize{12}Cond2, Group3'};
set(gca, 'xtick', dfs, 'xticklabel', names);
xlim([-1 26]);  %just for better visualisation
ylabel('\fontsize{14}Intensities')

I would like to group the dots with their errors bars pairwise. So the dot (point estimate) 1, 3, and 5 all belong to condition 1, while dots 2, 4 and 6 belong to condition 2. I mean just that there should be some indication that 1, 3, 5 belong to condition 1 and 2, 4, 6 to condition 2, for instance by a legend. But legend('Condition 1','Condition 2') does not work properly here. Putting all the information on the xaxis ticks is just too much content. Alternatively it would also be OK to make clear that the first 2 belong to group1, the next two to group2 etc.
What could be done?


Solution

  • For distinction, change the color of the dots and mention them in the legend. For your case, if there are a few conditions and many groups, it will be better to use conditions in the legend (which is your first stated required result). However, if there are a few groups and many conditions, it will be better to use groups in the legend (which you wrote as an alternative).

    For the first case, i.e. few conditions and many groups, replace your plot command with:

    h(1) = scatter(dfs(1:2:end),Intensities(1:2:end),'o','filled');
    h(2) = scatter(dfs(2:2:end),Intensities(2:2:end),'o','filled');
    %filling the dots so that your eyes may not dodge you about the colors :D
    %I choose 1:2:end and 2:2:end for the first and second lines since there seems to be
    %an order. If there is no order, you can explicitly state that as: [1 3 5] or [2 4 6]
    

    and then remove the line where you change xticklabels and use legend as:

    legend(h,'condition1','condition2');
    

    output1
    Fig 1: Less conditions, many groups


    For the second case, i.e. few groups and many conditions, replace your plot command with:

    for k=1:3
        h(k) = scatter(dfs([2*k-1 2*k]),Intensities([2*k-1 2*k]),'o','filled'); 
    end                    %     ^---------generalised the formula
    

    and then remove the line where you change xticklabels and use legend as:

    legend(h,'group1','group2','group3');
    

    output2
    Fig 2: More conditions, less groups