Change color order of legend

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.

 채택된 답변

Kelly Kearney
Kelly Kearney 2012년 7월 12일

0 개 추천

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

John Petersen
John Petersen 2012년 7월 12일
Just the kind of answer I was looking for. Thanks!
Moritz
Moritz 2012년 7월 13일
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 2012년 7월 17일
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.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Community Treasure Hunt

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

Start Hunting!

Translated by