Plotting multiple boxplots in same window...array for each boxplot is not the same length...causing error

12 views (last 30 days)
Wesser on 8 Jun 2021
Answered: dpb on 8 Jun 2021
Hi,
I'm trying to plot multiple boxplots in the same figure, but the column vectors associated with each boxplot are not the same length/dimension. ie the column vectors range in length between 31 and 102 data points. The only way I know to put more than one boxplot into the same plot is to create a matrix of the columns (see attached code) but this doesn't work when the column dimensions are not the same. Is there a workaround??
BoxSeciruty %column vector of 102 data points
BoxWidefield_123 %column vector of 71 data points
BoxWidefield_45 %column vector of 31 data points
BoxWidefield_all %column vector of 99 data points
BoxFountain %column vector of 57 data points
figure
BoxTowns = [BoxSeciruty BoxWidefield_123 BoxWidefield_45 BoxWidefield_all BoxFountain]; %trying to make a matrix of all the above data
boxplot(BoxTowns, 'labels', {'BoxSeciruty' 'BoxWidefield_123' 'BoxWidefield_45' 'BoxWidefield_all' 'BoxFountain_all'});
title('Average start of exposure based on residence (MC=10,000)');
Many thanks for your time and tips!!

dpb on 8 Jun 2021
Two ways to do it --
1. Use grouping variables and catenate the data into one long vector--
Data=[BoxSecurity; BoxWidefield_123; BoxWidefield_45; BoxWidefield_all; BoxFountain];
G=[repmat(1,BoxSecurity,1); repmat(1,BoxWidefield_123,1); repmat(1,BoxWidefield_45,1); ...
repmat(1,BoxWidefield_all,1); repmat(1,BoxFountain,1)];
boxplot(Data,G) % augment as desired
2. Augment the shorter vectors to same length as longest with NaN and created array of same-length columns
N=([numel(BoxSecurity); numel(BoxWidefield_123); numel(BoxWidefield_45); ...
numel(BoxWidefield_all); numel(BoxFountain)]);
nMax=max(N);
Data=[[BoxSecurity; nan(nMax-N(1),1)];[BoxWidefield_123; nan(nMax-N(1),1)];[BoxWidefield_45; nan(nMax-N(1),1)]; ...
[BoxWidefield_all; nan(nMax-N(1),1)]; [BoxFountain; nan(nMax-N(1),1)]];
boxplot(Data)
Your choice of which is less painful; note that either would be MUCH simpler if the data were in a cell array or other structure rather than similarly-spelled very-long-winded individual variables. The power of MATLAB is in the use of arrays and vector operations.

Categories

Find more on Exploration and Visualization in Help Center and File Exchange

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by