How to sorting categorical array for plotting
17 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Moh Rifqy Risqullah
el 25 de Abr. de 2023
Comentada: Moh Rifqy Risqullah
el 25 de Abr. de 2023
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
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1365864/image.jpeg)
Thanks for your help
0 comentarios
Respuesta aceptada
Stephen23
el 25 de Abr. de 2023
Editada: Stephen23
el 25 de Abr. de 2023
By default the categories are sorted into character order, not alphanumeric order.
S = "M"+(1:10);
A = categorical(S)
C = categories(A) % default order = sorted by character.
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 ...
categories(D) % but the categories are in the expected order.
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)
E = reordercats(A,natsort(categories(A)));
categories(E)
Once you have the categories in the required order, then your plot will look as you expect:
plot(E,Y);
Más respuestas (1)
dpb
el 25 de Abr. de 2023
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...
Ver también
Categorías
Más información sobre Shifting and Sorting Matrices en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!