Change color order of legend

3 views (last 30 days)
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.

Accepted Answer

Kelly Kearney
Kelly Kearney on 12 Jul 2012
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));
  3 Comments
Moritz
Moritz on 13 Jul 2012
Hi Kelly,
I always use this approach. But the problem is that after plotting, if you switch off the legend (I mean by clicking on its icon) and again switch on, it will show all the lines data, not only the ones which we stored their handles.
Do you have any easy workaround for this?
Kelly Kearney
Kelly Kearney on 17 Jul 2012
Well, I'm a command-line girl... I never use any of the pointy-clicky options, so I'm not quite sure what they do. My guess is it must delete the legend, then recreate it for the entire axis. Rather than clicking on the legend to hide it, try using
set(hleg, 'visible', 'off');
where hleg is the handle to the legend. That way, the object still exists exactly as you defined it, and can be made visible again when you need it.

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!