How to reorder a categorical axis?

125 ビュー (過去 30 日間)
Zhe Dong
Zhe Dong 2023 年 3 月 14 日
編集済み: Zhe Dong 2023 年 3 月 15 日
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];
scatter(x,y);
how do I plot y aginst x so the x-axis appears in a non-alphabetical order, like b-e-d-a-c.
thanks!

採用された回答

Dave B
Dave B 2023 年 3 月 14 日
編集済み: Dave B 2023 年 3 月 14 日
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;
scatter(x,y);
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;
scatter(x,y);
xaxis=get(gca,'XAxis');
xaxis.Categories={'b' 'e' 'd' 'a' 'c'};
  2 件のコメント
VBBV
VBBV 2023 年 3 月 15 日
編集済み: VBBV 2023 年 3 月 15 日
% Fourth option is you can use find to get indices for array and pass it to
% xticklabels
x = categorical({'a','b','c','d','e'});
new_x = {'b','e','d','a','c'};
for k = 1:length(x)
idx(k) = find(new_x(k) == x);
end
y = 1:5;
scatter(x,y(idx));
xticklabels(x(idx))
% strange output using scatter
x(idx)
ans = 1×5 categorical array
b e d a c
% even though idx values are substituted, when i use it scatter function
% it still retains old order
scatter(x(idx),y(idx))
Zhe Dong
Zhe Dong 2023 年 3 月 15 日
Many thanks, it helps!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeAnnotations についてさらに検索

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by