MATLAB: Wrong ‘patch’ area when plotting

groupingMATLABpatchplotting

Hello Community,
I am using the 'patch' function to plot 4 areas to aid with the grouping of some data when it is plotted. I have tried to make the code so that it will work with any size of plot, hence defining the x-limits (x_lim). The problem is, with the code I have written, the patches dont align as I would like:
% Define limits of axis
x_lim = get(gca,'xlim');
y_lim = get(gca,'ylim');
% Colour in the patches
patch([0 0 (x_lim(1,2)/4) (x_lim(1,2)/4)],[y_lim(1) y_lim(2) y_lim(2) y_lim(1) ],[1 0.5 0.2],'FaceAlpha',0.2)
patch([(x_lim(1,2)/4) (x_lim(1,2)/4) ((x_lim(1,2)/4)*2) ((x_lim(1,2)/4)*2) ],[y_lim(1) y_lim(2) y_lim(2) y_lim(1) ],[1 1 0.2],'FaceAlpha',0.2)
patch([((x_lim(1,2)/4)*2) ((x_lim(1,2)/4)*2) ((x_lim(1,2)/4)*3) ((x_lim(1,2)/4)*3)],[y_lim(1) y_lim(2) y_lim(2) y_lim(1) ],[0.5 1 0.7],'FaceAlpha',0.2)
patch([((x_lim(1,2)/4)*3) ((x_lim(1,2)/4)*3) x_lim(2) x_lim(2)],[y_lim(1) y_lim(2) y_lim(2) y_lim(1) ],[0.4 0.3 0.8],'FaceAlpha',0.2)
and they produce this plot:
What I would like to happen is that the patch groups around the first 4 box plots (group A), then the next patch covers the next 4 boxplots (group B) and so on.
I have tried various combinations of my code but haven't managed to get this to work in the way that I want. Can anyone offer a bit of help to resolve this please?
Kind regards,
10B.

Best Answer

You will have to define the patch x-values to correspond to the x-values of your data instead of segments of the x-axis. Define them for instance as the mean value of the 4th and 5th, 8th and 9th, and so for the rest.