필터 지우기
필터 지우기

How to sorting categorical array for plotting

조회 수: 17 (최근 30일)
Moh Rifqy Risqullah
Moh Rifqy Risqullah 2023년 4월 25일
댓글: Moh Rifqy Risqullah 2023년 4월 25일
Hi everyone,
I have categorical array that use to plot. But in the plot, the x-axis isn't numerically. Its plot from M1, M10, M2, M3...M9 instead M1,M2,...M10
male=MakeMaleSample(10);
male=categorical(male);
data_male=[1:10];
plot(male,data_male);
grid on
function male=MakeMaleSample(n)
male="M"+string(1:n);
end
Thanks for your help

채택된 답변

Stephen23
Stephen23 2023년 4월 25일
편집: Stephen23 2023년 4월 25일
By default the categories are sorted into character order, not alphanumeric order.
S = "M"+(1:10);
A = categorical(S)
A = 1×10 categorical array
M1 M2 M3 M4 M5 M6 M7 M8 M9 M10
C = categories(A) % default order = sorted by character.
C = 10×1 cell array
{'M1' } {'M10'} {'M2' } {'M3' } {'M4' } {'M5' } {'M6' } {'M7' } {'M8' } {'M9' }
Y = 1:10;
plot(A,Y);
Solution one: You can specify the order when creating the categorical array:
D = categorical(S, "M"+(1:10)) % looks the same as A ...
D = 1×10 categorical array
M1 M2 M3 M4 M5 M6 M7 M8 M9 M10
categories(D) % but the categories are in the expected order.
ans = 10×1 cell array
{'M1' } {'M2' } {'M3' } {'M4' } {'M5' } {'M6' } {'M7' } {'M8' } {'M9' } {'M10'}
Solution two: change the category order of an existing categorical array using REORDERCATS, e.g.:
[~,X] = sort(str2double(replace(C,"M","")));
B = reordercats(A,C(X));
categories(B)
ans = 10×1 cell array
{'M1' } {'M2' } {'M3' } {'M4' } {'M5' } {'M6' } {'M7' } {'M8' } {'M9' } {'M10'}
Solution three: For compactness you could also use NATSORT (must be downloaded here):
E = reordercats(A,natsort(categories(A)));
categories(E)
ans = 10×1 cell array
{'M1' } {'M2' } {'M3' } {'M4' } {'M5' } {'M6' } {'M7' } {'M8' } {'M9' } {'M10'}
Once you have the categories in the required order, then your plot will look as you expect:
plot(E,Y);

추가 답변 (1개)

dpb
dpb 2023년 4월 25일
function male=MakeMaleSample(n)
male=categorical("M"+1:n,"M"+1:n);
end
To force a non-lexical sort order, you have to specify the specific order explicitly...

카테고리

Help CenterFile Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by