MATLAB: Re-order legend but mismatch colour

legendorder

I want to differentiate my data in a scattered plot based on the source of data, e.g. USA, Italy, UK and France. I realised that the order they appear in the legend is in alphabetical order (default setting?), that is, France, Italy, UK and USA. When I changed their order in the legend, the data did not match with the colour. Any ideas?
f1 = gscatter(x, y, country, 'ygbr'); %by default, the output of this is France(y), Italy(g), UK (b), USA(r)
get(legend(), 'String');
neworder = [3 4 2 1]; % I want it to appear as: UK(b), USA(r), Italy(g), France(y)
legend([f1], labels (neworder)); % the output is: UK(y), USA(g), Italy(b), France(r)

Best Answer

You need to reorder the handle as well. Something like this ...
legend(f1(neworder), labels(neworder))
Here is an example adapted from the documentation for gscatter:
load discrim
figure
f1 = gscatter(ratings(:,1),ratings(:,2),group,'br','xo');
legendText = {'g1','g2'};
newOrder = [2 1];
legend(f1(newOrder),legendText(newOrder))