Plotting grouped box plot of varying lengths
92 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
How do i do a plot several groups of box plot with varying length?
Example:
trial1 = rand(5,7);
trial2 = rand(10,7);
trial3 = rand(15,7);
What i want is column 1 of trial1, trial2 and trial3 boxplot to group as category 1, column 2 of trial 1, trial 2 and trial 3 as category 2 and so on to be displayed in a single box plot. What I search is the number of rows need to be the same but for this case it is not. x = rand(5,2);
y = rand(10,2);
z = rand(15,2);
0 commentaires
Réponses (1)
Dave B
le 19 Mar 2022
First of all, if you use boxchart (released in R2020a) you'll have a bit more flexibility than the old boxplot function.
The way I interpreted what you were asking for is, two grouping factors: one should be grouping by which column of the matrix, and the other should be grouping by which matrix. To accomplish this with boxchart it's easier to specify data as vectors rather than matrices, this let's you explicitly specify the xgroupdata argument and the cgroupdata argument.
You'll need to choose which one you want to be represented by color and which you'll want for x - I think from your description you're looking for 7 sets of 3 boxes (so color is 'which matrix' and x is 'which column'. But if I got that wrong you can just reverse them.
Finally, I added a little multiplier to the x so that there was a little space between each set of 3 boxes. I think that makes it a little easier to see, but it means having to set the XTicks/XTickLabels explitily.
You could make the below code much more compact, I spread it out so you could see my logic:
% Sample Data:
trial1 = rand(5,7);
trial2 = rand(10,7);
trial3 = rand(15,7);
% These grouping matrices label the columns:
grp1 = repmat(1:7,size(trial1,1),1);
grp2 = repmat(1:7,size(trial2,1),1);
grp3 = repmat(1:7,size(trial3,1),1);
% These color matrices label the matrix id:
clr1 = repmat(1,size(trial1));
clr2 = repmat(2,size(trial2));
clr3 = repmat(3,size(trial3));
% Combine the above matrices into one for x, y, and c:
x = [grp1;grp2;grp3];
y = [trial1;trial2;trial3];
c = [clr1;clr2;clr3];
% Convert those matrices to vectors:
x = x(:);
y = y(:);
c = c(:);
% Multiply x by 2 so that they're spread out:
x = x*2;
% Make the boxchart,
boxchart(x(:),y(:),'GroupByColor',c(:))
% Set the x ticks and labels, and add a legend
xticks(2:2:14);
xticklabels(1:7)
xlabel('Category')
legend(["Trial 1" "Trial 2" "Trial 3"],'Location','NorthOutside')
Voir également
Catégories
En savoir plus sur Data Distribution Plots dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!