How do I get multiple boxplots onto one figure, with NaNs in the mix?

36 views (last 30 days)
Hi,
I've been trying to get 3 plots on one figure and have mostly gotten there, but my code keeps throwing the error: "G must be the same length as X or the same length as the number of columns in X," even though these 2 variables are the same lengths. I can't help but think it's the NaNs, even though I've read that boxplot treats them correctly. Code to follow:
First, I created these vectors as I am compiling group data and generating a mean. With that mean, I want to plot in terms of the scalae (which is the ST, SM, and SV variables).
meanampST = [meanampST peakmeanST]; meanampSM = [meanampSM peakmeanSM]; meanampSV = [meanampSV peakmeanSV];
After those are filled:
group = [ones(size(meanampST));2*ones(size(meanampSM)); 3*ones(size(meanampSV))]; x = cat(1,meanampST,meanampSM,meanampSV); boxplot(x,group);
..and then I get the error. For reference:
x =
0.1043 0.1488 NaN 0.0628 0.1959 0.2604 0.0674 0.0477
0.2905 0.2177 0.0814 0.0793 0.3609 0.1885 NaN 0.0478
NaN NaN 0.0671 0.1126 NaN NaN NaN 0.1584
group =
1 1 1 1 1 1 1 1
2 2 2 2 2 2 2 2
3 3 3 3 3 3 3 3
UGGH! Thank you so much!

Accepted Answer

Kelly Kearney
Kelly Kearney on 15 Aug 2014
Just a small change needed:
boxplot(x(:), group(:))
  3 Comments
Kelly Kearney
Kelly Kearney on 15 Aug 2014
From the help:
boxplot(X,G) specifies one or more grouping variables G, producing a separate box for each set of X values sharing the same G value or values. Grouping variables must have one row per element of X, or one row per column of X. Specify a single grouping variable in G by using a vector, a character array, a cell array of strings, or a vector categorical array; specify multiple grouping variables in G by using a cell array of these variable types, such as {G1 G2 G3}, or by using a matrix. If multiple grouping variables are used, they must all be the same length. Groups that contain a NaN or an empty string ('') in a grouping variable are omitted, and are not counted in the number of groups considered by other parameters.
so you can get your desired plot via a few syntaxes:
boxplot(x')
boxplot(x(:), group(:))
boxplot(x', group(:,1))
(Though that last one would only be useful if you wanted to rearrange the order the boxes were displayed).
As for colors, you can set them via the 'colors' input parameter:
h = boxplot(x', 'colors', 'rgb')
or you can alter all the line properties by returning the handles, as I did above (you can see which handle corresponds to which part of the boxplot by looking at their Tag properties).

Sign in to comment.

More Answers (1)

Haijun Deng
Haijun Deng on 17 Dec 2018
boxplot(x','ori','horizontal')
figure2.png

Community Treasure Hunt

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

Start Hunting!