How can I adjust boxchart to have different number of groups for different nr of classes?
3 views (last 30 days)
Show older comments
I would like to change this graph by keeping 4 boxplots for 4 and 6 classes, and then having only blue and red boxplots for 8 classes.
2 Comments
the cyclist
on 12 Sep 2024
There are a couple different possible approaches here.
One approach would be on the data side, which would be to replace the 8-classes yellow and purple data points with NaN values (or delete them), so that they don't "exist" to be plotted.
A second approach would be on the plotting side, which would be to identify those two boxes, and set their "Visible" property to "Off". (I am not 100% certain one can do this for individual boxes.)
Either way, if you upload the data and code you used to produce the plot, it will be easier to provide a solution.
Accepted Answer
Jatin
on 12 Sep 2024
Based on my understanding, you want to create a 'boxchart' with a different number of classes for each group. You can accomplish this by utilizing the 'GroupByColor' property of 'boxchart', which allows MATLAB to color the box plots within each group according to the different classes you've specified.
Here’s an example code snippet demonstrating the use of 'GroupByColor':
% Sample data setup
data = randn(100, 1);
group = [ones(30,1); 2*ones(50,1); 3*ones(20,1)]; % Groups 1, 2, 3
class = [randi([1, 2], 30, 1); randi([1, 3], 50, 1); randi([1, 1], 20, 1)]; % Different number of classes per group
% Plotting the boxchart
figure;
boxchart(group, data, 'GroupByColor', class);
xticks([1 2 3]);
xticklabels({'Group 1', 'Group 2', 'Group 3'});
% Adding labels
xlabel('Group');
ylabel('Data');
title('Box chart with different number of groups and classes');
Kindly refer the below documentation to read more on 'GroupByColor' property:
Feel free to attach your data file if you're still encountering issues.
3 Comments
Jatin
on 13 Sep 2024
Edited: Jatin
on 13 Sep 2024
Hello Marietta,
The appearance of the class boxes is determined by the data itself, and there isn't a specific property to increase the distance between groups. However, you can adjust the group locations by modifying the group data, as demonstrated in the code below:
% Sample data setup
data = randn(100, 1);
group = [ones(30,1); 4*ones(50,1); 7*ones(20,1)]; % Groups 1, 2, 3
class = [randi([1, 2], 30, 1); randi([1, 3], 50, 1); randi([1, 1], 20, 1)]; % Different number of classes per group
% Plotting the boxchart
figure;
boxchart(group, data, 'GroupByColor', class);
% Setting x-axis ticks and labels
xticks([1 4 7]);
xticklabels({'Group 1', 'Group 2', 'Group 3'});
% Adding labels
xlabel('Group');
ylabel('Data');
title('Box chart with increased distance between groups');
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!