MATLAB: Change color order of legend

colorslegendplot

I have a number of parameters that I want to plot or not plot based on whether the user selects them in a GUI. If a parameter isn't selected, I reassign the values to NaN so they don't plot. Here I'll just include 3 parms as an example. I also fill legend text based on the selections.
ind = 1;
if flag1; legendtext{ind}='y1'; ind=ind+1; else y1 = y1*NaN; end
if flag2; legendtext{ind}='y2'; ind=ind+1; else y2 = y2*NaN; end
if flag3; legendtext{ind}='y3'; ind=ind+1; else y3 = y3*NaN; end
plot(h, x1,y1,x2,y2,x3,y3)
legend(h, legendtext)
The plot always plots y1 as blue, y2 as green and y3 as red because if any are NaNs, they act as placeholders for the colors. But if flag1 or flag2 is not set then the legend colors do not match the plot colors. I could add plot(h,xi,yi) to every test, but I want to know if I there is another way.

Best Answer

Rather than pointing the legend to the axis, pass the handles of the individual lines. This way you can specify exactly which lines to label. Also, not sure if your actually using flag1, flag2, y1, y2, etc. as variable names or if that's just part of the toy example, but using matrices or cell arrays would be more efficient. I'll use cell arrays in this example, in case your datasets are different lengths.
flag = [false true false];
x = {1:10, 2:2:10, 1:10};
y = {rand(10,1), rand(5,1), rand(10,1)};
legendtext = {'one', 'two', 'three'};
xy = [x;y];
h = axes;
hln = plot(h, xy{:});
set(hln(~flag), 'visible', 'off');
legend(hln(flag), legendtext(flag));