Separator in X-axis and 2 Box plots per range

조회 수: 6 (최근 30일)
Huy Nguyen Duc
Huy Nguyen Duc 2021년 12월 13일
답변: Abhinaya Kennedy 2024년 2월 14일
Hello everyone,
Currently I have 2 sets of data: Type A with 3 sizes(1 kg, 2 kg, and 3 kg), and Type B with similar sizes(1, 2, 3 Kg). Each weight has multiple value to draw a box plot. I want my box plot to be similar as shown below but have no idea how to, first, separate x-axis with vertical lines and, second, put 2 box plots of the same weight in a range. Below is a similar figure I want my figure to be.
How can I do this one?
Thank you, Huy Nguyen.

답변 (1개)

Abhinaya Kennedy
Abhinaya Kennedy 2024년 2월 14일
Hi,
To create a box plot in MATLAB that separates the x-axis with vertical lines and groups two box plots of the same weight together, you can use the following MATLAB code and replace it with your data. This code will create two box plots for each weight, one for Type A and one for Type B, and place vertical lines between the different weight groups.
% Sample data for Type A and Type B for each weight
size_1kg_A = [value1, value2, value3, ...]; % Replace with your actual data
size_2kg_A = [value1, value2, value3, ...];
size_3kg_A = [value1, value2, value3, ...];
size_1kg_B = [value1, value2, value3, ...];
size_2kg_B = [value1, value2, value3, ...];
size_3kg_B = [value1, value2, value3, ...];
% Combine data into a cell array for plotting
data = {size_1kg_A, size_1kg_B, size_2kg_A, size_2kg_B, size_3kg_A, size_3kg_B};
% Create a grouped box plot
boxplot(cell2mat(data'), 'Notch', 'on', 'Labels', {'1kg A', '1kg B', '2kg A', '2kg B', '3kg A', '3kg B'}, 'Whisker', 1.5)
% Add vertical lines to separate different weights
hold on;
xL = xlim;
line([2.5 2.5], xL, 'Color', 'k', 'LineStyle', '--');
line([4.5 4.5], xL, 'Color', 'k', 'LineStyle', '--');
hold off;
% Add labels and title
xlabel('Weight and Type');
ylabel('Values');
title('Box Plot of Weights for Type A and B');
% Adjust x-axis to have ticks in the middle of each pair
set(gca, 'xtick', [1.5 3.5 5.5]);
set(gca, 'xticklabel', {'1 kg', '2 kg', '3 kg'});
% Display the box plot
grid on;
You can find additional information on boxplots here: https://www.mathworks.com/help/stats/boxplot.html
Hope this helps!

카테고리

Help CenterFile Exchange에서 Graphics Objects에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by