How to plot box plots of data of different sizes on the same figure?

Hi everyone!
I have vectors of variable sizes in a cell array. I need to plot the box plot of each vector on the same figure. The Matlab function boxplot accepts only a matrix as an input, meaning that I cannot plot all the boxes together by passing a cell array. Also, it doesn't work if I hold the axes and plot the boxes one by one at different positions. A simple code is below to help you understand the issue.
x1 = randn(128, 1);
x2 = randn(100, 1);
figure
boxplot(x1, 'Positions', 1);
hold on
boxplot(x2, 'Positions', 2);
% only one box is shown

 Accepted Answer

You just need to define a grouping array:
x1 = randn(128, 1);
x2 = randn(100, 1);
X = [x1; x2];
grp = [ones(size(x1)); 2.*ones(size(x2))];
boxplot(X, grp)

5 Comments

Thanks! Are you aware of a way to do that by holding the axes, so that I don't need to accumulate the data?
Nope afik! but I don't understand why you need that while this is clearly easier and faster. Anyways, you can avoid accumulating by:
x1 = randn(128, 1);
x2 = randn(100, 1);
boxplot([x1; x2], [ones(size(x1)); 2.*ones(size(x2))]) % so, no merged arrays!
Saying that it is easier is completely subjective, as it depends on the code. I am reading data from different files and plotting different visualizations on different panels. Once new data is read, I use it for plotting on different panels, some of which have their axes held. It is much easier to draw the data once read, than storing it in a huge multidimensional matrix then plot.
After checking again the boxplot behavior, I guess there is a workaround to avoid this grouping:
x1 = randn(128, 1);
x2 = randn(100, 1);
ax = gca;
hold on
boxplot(ax, x1, 'Position', 1)
boxplot(ax, x2, 'Position', 2)
hold off
% modify XLim and YLim so that the axis covers both datasets.
ax.XLim = [0.5, 2.5]; % Make sure that ax XLim covers both
YLimCoeff = 1.1;
ax.YLim = [YLimCoeff*min([x1(:); x2(:)]), YLimCoeff*max([x1(:); x2(:)])]; % so, even if x1 and x2 come from different sources, by now, both are available
% modify XTick: current axis only has the tick value for the second boxplot
ax.XTick = [1, 2];
ax.XTickLabel = string(ax.XTick);

Sign in to comment.

More Answers (0)

Products

Release

R2019b

Asked:

on 13 Jul 2021

Commented:

on 15 Jul 2021

Community Treasure Hunt

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

Start Hunting!