I created a histogram from data I extracted from a table. The input is as displayed in "size".
size = ["large" "xlarge" "small" "small" "medium" "large" "xlarge" "small" "medium" "medium" "xlarge"];
C = categorical(size);
h = histogram(C);
% right order would be:
X = [4 1 2 3];
Y = ["xlarge" "small" "medium" "large"];
[Xsorted,I] = sort(X);
Ysorted = Y(I);
%h.DisplayOrder = Ysorted;
This plot is what I get:
The command DisplayOrder only regognizes 'descend' or 'ascend'. As default the data is in order of the input data.
Is there a possibility to order the data according to Y?

 채택된 답변

Steven Lord
Steven Lord 2022년 12월 8일

0 개 추천

Specify the valueset in the order in which you want the categories to be listed when you construct the categorical array.
BTW, don't name a variable size. That already has a meaning in MATLAB.
sizes = ["large" "xlarge" "small" "small" "medium" "large" "xlarge" "small" "medium" "medium" "xlarge"];
Y = ["small" "medium" "large" "xlarge" ];
C = categorical(sizes, Y);
h = histogram(C);
Alternately use reordercats on the categorical array after the fact.
C2 = categorical(sizes);
categories(C2) % Note the order; look familiar from your original example?
ans = 4×1 cell array
{'large' } {'medium'} {'small' } {'xlarge'}
C2 = reordercats(C2, Y);
categories(C2) % Note the new order
ans = 4×1 cell array
{'small' } {'medium'} {'large' } {'xlarge'}
figure
histogram(C2)

댓글 수: 2

Katrin Niedermeier
Katrin Niedermeier 2022년 12월 8일
Thank you, that was easier than expected!
By the way, since your data sounds like it has an inherent ordering (small < medium, medium < large, etc.) you might want to create it as ordinal data. Looking at a sample of your data:
sizes = ["large" "xlarge" "small" "small" "medium"];
Y = ["small" "medium" "large" "xlarge" ];
orderedC = categorical(sizes, Y, Ordinal=true)
orderedC = 1×5 categorical array
large xlarge small small medium
unorderedC = categorical(sizes, Y)
unorderedC = 1×5 categorical array
large xlarge small small medium
You could create a histogram with either:
subplot(1, 2, 1)
histogram(orderedC)
subplot(1, 2, 2)
histogram(unorderedC)
But the ordinal categorical lets you ask questions like:
orderedC(2) < orderedC(3) % Is xlarge < small? false
ans = logical
0
orderedC(1) < orderedC(2) % Is large < xlarge? true
ans = logical
1
You can't ask those same questions for the non-ordinal categorical.
unorderedC(2) < unorderedC(3)
Error using <
Relational comparisons are not allowed for categorical arrays that are not ordinal.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Histograms에 대해 자세히 알아보기

제품

릴리스

R2022b

질문:

2022년 12월 8일

댓글:

2022년 12월 8일

Community Treasure Hunt

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

Start Hunting!

Translated by