Search code examples
matlabsortingcategorical

Plot values in ascending order with reordered categorical elements accordingly (Matlab)


I would like to plot values (in the y axis) attached to categorical data (strings in the x axis) in ascending order, with the reordering of the elements in the x axis accordingly.

My code is similar to this example:

s = cellstr(["A";"B";"C";"D"]); % Original data
y = [5; 0.5; 7.8; 2]; % Original data

[~,n_sort] = sort(y);
x = categorical(s);
x_sort = reordercats(x,n_sort);
scatter(x_sort,y(n_sort))

I expected it to be [B, D, A, C] on x axis and [0.5, 2, 5, 7.8] for the y axis. But instead, I got this: output So the order of the x axis elements is satisfactory, but the values follows a strange order that I have not figured out (in my original code). In the example here, it is in the reverse order of original y, yet I found no reason for that to happen.

I am curious to know the explanation behind this, and seek an alternative code. Thank you in advance.


Solution

  • To fix your code replace the last line with:

    scatter(x_sort,y)
    

    The scatter function automatically sorts the y axis when the categorical array has been reordered so you sort twice by including y(n_sort).