How to reorder a categorical axis?

72 views (last 30 days)
Zhe Dong
Zhe Dong on 14 Mar 2023
Edited: Zhe Dong on 15 Mar 2023
I am ploting a set of values aginst an categorical array, however the the categorical axis always appears in the alphabetical order, how can I control the order it appears?
here's an example
x = categorical({'a','b','c','d','e'});
y = [1:5];
how do I plot y aginst x so the x-axis appears in a non-alphabetical order, like b-e-d-a-c.

Accepted Answer

Dave B
Dave B on 14 Mar 2023
Edited: Dave B on 14 Mar 2023
Three options to change the order, depending on where you want to change it:
Option 1: You can use reordercats to re-order the categories:
x = categorical({'a','b','c','d','e'});
y = 1:5;
orderedx = reordercats(x,{'b' 'e' 'd' 'a' 'c'});
scatter(orderedx ,y);
Or you can pass in the order as an input to categorical:
x = categorical({'a','b','c','d','e'}, {'b' 'e' 'd' 'a' 'c'});
y = 1:5;
Or you can change the order on the axes using the Categories property of the CategoricalRuler:
x = categorical({'a','b','c','d','e'});
y = 1:5;
xaxis.Categories={'b' 'e' 'd' 'a' 'c'};
Zhe Dong
Zhe Dong on 15 Mar 2023
Many thanks, it helps!

Sign in to comment.

More Answers (0)




Community Treasure Hunt

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

Start Hunting!