MATLAB: Display mean of data on a boxchart

MATLABplot

I need to show the mean of each box plot on the figure. here is the code to generate my box plot:
x = 1:numel(data);
colors = rand(numel(data), 3);
figure();
ax = axes();
hold(ax);
for i=1:numel(data)
boxchart(x(i)*ones(size(data{i})), data{i},'MarkerStyle','none', ...
'BoxFaceColor', colors(i,:), ...
'LineWidth', 0.5, ...
'WhiskerLineStyle', '-')
end
set(gca,'xtick',[])
When I had just one boxplot I simply used this line:
hold on
plot(mean(x), '*')
But here when I use it in the code:
x = 1:numel(data);
colors = rand(numel(data), 3);
figure();
ax = axes();
hold(ax);
for i=1:numel(data)
boxchart(x(i)*ones(size(data{i})), data{i},'MarkerStyle','none', ...
'BoxFaceColor', colors(i,:), ...
'LineWidth', 0.5, ...
'WhiskerLineStyle', '-')
plot(mean(data{i}), '*') %%%%%%%%%%<<<<<<<<<<<<< HERE
end
set(gca,'xtick',[])
It shows all mean values on the first boxplot only, meanwhile I need to have one * as a mean value for each boxplot.
Best Regards

Best Answer

"??? There's a boxplot, no info on boxchart"
Well, bless their little pea-pickin' hearts but TMW has done it again...introduced yet another duplicated function with different name and slightly different syntax/characteristics. I wish they would quit doing that and do something really new and different like introduce a hatching pattern or something instead...
Anyways my rant aside, looks like you're going at this the hard way. Reading between the lines, it looks like you have a cell array of numel() elements and you're iterating over it to plot each cell separately.
Instead
figure;
y=cellmat(data); % convert the cell array to matrix
hBx=boxchart(y,'MarkerStyle','none', ... % do the box plot
'BoxFaceColor', colors(i,:), ...
'LineWidth', 0.5, ...
'WhiskerLineStyle', '-');
hold on
hLmn=plot(1:size(y,2),mean(y), '*','r'); % and the stars for means
hAx=gca;
hAx.XTick=[];
Only two caveats:
  1. each element in data is same number points; if this isn't so, will need to augment the shorter cells to length of longest with NaN, and
  2. the data in each cell are column vectors--if rows, then transpose the y array before calling boxchart
You can stick with the existing way of generating an unneeded x variable to fake out barchart by giving an artificial grouping variable, but that's kinda' messy way. If they were going to write a new one, don't know why didn't allow for an x axis variable while at it other than simply the only grouping variable option.
N=numel(data);
colors = rand(N, 3);
figure;
hAx = axes();
hold on
for i=1:N
boxchart(i*ones(size(data{i})), data{i},'MarkerStyle','none', ...
'BoxFaceColor', colors(i,:), ...
'LineWidth', 0.5, ...
'WhiskerLineStyle', '-')
plot(i,mean(data{i}),'*r') % you didn't put in an x coordinate so all plotted at 1,mean(y)
end
set(gca,'xtick',[])
I'd recommend looking at vectorizing instead of the latter, though...