How to improve groups in boxplot matlab?

8 views (last 30 days)
Hi everybody!
I'm trying to create a boxplot with multiple variables.
This is my code:
h = boxplot(L_levtrue,{ID_stop_levtrue,Nn_levtrue,Litol_levtrue},'ColorGroup',Litol_levtrue);
And this is the output:
The variable I used to create the boxplot is L_levtrue. I would like to create a unique label based on ID_stop_levtrue (the numbers 3203, 3203 etc..) and a vertical line which separate these groups. I attached my data here.
Can anybody help me?
Thanks in advance!!

Accepted Answer

Adam Danz
Adam Danz on 19 Dec 2020
To add vertical lines that separate groups from the first grouping variable, add 'FactorSeparator',1.
h = boxplot(L_levtrue,{ID_stop_levtrue,Nn_levtrue,Litol_levtrue},'ColorGroup',Litol_levtrue,'FactorSeparator',1);
  3 Comments
Adam Danz
Adam Danz on 20 Dec 2020
There might be a better way to do this but the demo below replaces the strings in row 1 of the labels with the strings in row2, then replaces the labels in row 2 with the labels in row 3, and then replaces the first label in each group of row 3 with the unique label for the group.
The loop that's commented-out at the end centers that label but a listener created in the boxplot function will reposition those labels any time the figure is resized.
Alternatively you could remove the 3rd row of labels and put the text within the figure at the top, center of each group.
h = boxplot(L_levtrue,{ID_stop_levtrue,Nn_levtrue,Litol_levtrue},'ColorGroup',Litol_levtrue,'FactorSeparator',1);
tx = findobj(gca,'Type','Text');
txPos = cell2mat(get(tx,'Position'));
txStr = {tx.String};
% Remove first row of text and shift 2nd and 3rd rows upward
% The first row of text will be toward the end of the text handle array
textrow = [repelem([3;2;1], size(h,2),1), repmat((1:size(h,2))', 3,1)];
% Store the text from 1st row
[row1labels,grpIdx] = unique(txStr(textrow(:,1)==1),'stable');
% Move rows 2 and 3 to rows 1 and 2.
drawnow(); pause(.05)
set(tx(textrow(:,1)==1), {'String'}, txStr(textrow(:,1)==2)')
set(tx(textrow(:,1)==2), {'String'}, txStr(textrow(:,1)==3)')
% Remove all but one label per group in row 3
row3tx = flipud(tx(textrow(:,1)==3));
delete(row3tx(~ismember(1:numel(row3tx),grpIdx)));
row3tx(~ismember(1:numel(row3tx),grpIdx)) = [];
% Set remaining label to the unique group label
set(row3tx, {'String'}, row1labels(:))
% % Center the group label
% for i = 1:numel(row3tx)
% row3tx(i).Position(1) = mean(txPos(strcmp(txStr,row3tx(i).String),1));
% drawnow(); pause(.05)
% end

Sign in to comment.

More Answers (0)

Tags

Community Treasure Hunt

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

Start Hunting!