MATLAB: How to make multiple boxplots in one axes

boxplotwhisker plot

I found this link regarding my question:
for a sample data. But did not explain how those your data input should look like.
I found this pre-built function:
but I prefer to use standard mathwork function:
Any idea how to add inputs so like the one in the first link?

Best Answer

Here are several ways to add boxplots to an axis at specific x coordinates. The first two methods involve padding the input array with NaN values to offset the box plots along the x axis.
Add additional boxplots with matrix input.
Plot multiple boxplots with matrix input. One boxplot will be created per column.
% produce 6 boxplots at x = 1:6
cla()
boxplot(rand(5,3))
200130 225201-Figure 1.png
To horizontally offset the boxplots to start at x = n, pad n-1 columns of NaN values to the start of the matrix.
% Add two columns starting at x=4
hold on
data = rand(10,2);
nanPad = nan(10,3);
boxplot([nanPad, data])
200130 225320-Figure 1.png
Add additional boxplots with vector and grouping variable input
Plot multiple boxplots with a vector and a grouping variable.
cla()
x = 1:60;
group = repelem(1:3,1,20);
boxplot(x,group)
200130 225639-Figure 1.png
To horizontally offset the boxplots to start at x = n, start the grouping variable at n and pad n-1 NaN values to the start of the first input vector. Assign the grouping variable values 1:n for those padded values.
hold on
data2 = 1:40;
group2 = repelem(4:5,1,20); % grouping variable starts at n
% The rest of the code is adaptive.
nanPad = nan(1,min(group2)-1);
boxplot([nanPad,data2],[1:min(group2)-1,group2])
axis tight
xlim([min(xlim)-range(xlim)*.05, max(xlim)+range(xlim)*.05]) % +/- 5% of axis range

ylim([min(ylim)-range(ylim)*.05, max(ylim)+range(ylim)*.05]) % +/- 5% of axis range
200130 232025-Figure 1.png
Use the position property
This method has been recommended elsewhere but can be problematic. The demo below illustrates the problem of x tick label disappearing (r2019a).
boxplot(rand(1,200),repelem(1:2,1,100),'positions',[1,2], 'labels', [1,2])
hold on
boxplot(rand(1,200),repelem(3:4,1,100),'positions',[3,4], 'labels', [3,4])
axis tight