Histogram set custom DisplayOrder

1 view (last 30 days)
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?

Accepted Answer

Steven Lord
Steven Lord on 8 Dec 2022
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 Comments
Steven Lord
Steven Lord on 8 Dec 2022
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.

Sign in to comment.

More Answers (0)

Products


Release

R2022b

Community Treasure Hunt

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

Start Hunting!