Adding means to separate boxplots in the same figure window?

Hello,
I have combined two boxplots into the same figure window but when i go to add the means i seem to be doing something wrong as both means appear on only one of the boxplots:
I was wondering how i can correctly place the means onto the correct boxplots?
The matlab code code i used is:
figure(1)
boxchart([x2,x]);
grid on;
grid minor;
hold on;
plot(mean(x2),'xr');
plot(mean(x),'xr');
hold off;
legend(["","Mean Value"]);
hold off;

 Accepted Answer

When you call plot with one vector argument, that argument is treated as y and x is implicitly taken to be 1:numel(y). Since mean(x2) and mean(x) are both scalars, you get x = 1 in both of those plot calls. To avoid this behavior, explicitly specify the x-coordinate(s) to plot at:
x2 = rand(10,1);
x = rand(10,1);
figure(1)
boxchart([x2,x]);
grid on;
grid minor;
hold on;
plot(1,mean(x2),'xr'); % using x = 1 for x2 (1st column of the matrix sent to boxchart)
plot(2,mean(x),'xr'); % using x = 2 for x (2nd column of the matrix sent to boxchart)
hold off;
legend(["","Mean Value"]);
hold off;

More Answers (0)

Categories

Products

Release

R2022b

Asked:

on 20 Dec 2022

Edited:

on 20 Dec 2022

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!