How to change color of lines on legend?

239 views (last 30 days)
Mahdi Torabi
Mahdi Torabi on 14 Jul 2018
Commented: Simone on 29 Jan 2025 at 15:04
Is there any way to change the color of lines in the legend AFTER plotting the graph(like using Edit\axes properties)?
  5 Comments
Mahdi Torabi
Mahdi Torabi on 14 Jul 2018
Thank you so much. This solved the problem.
Simone
Simone on 29 Jan 2025 at 15:04
Thank you so much, clean and effective. I used your solution to ignore a very high amount of line() plots from the legend, while your code just builds the legend manually using as trick void but coloured plots. The syntax used is: legend(subset, labels).

Sign in to comment.

Accepted Answer

Mahdi Torabi
Mahdi Torabi on 14 Jul 2018
Edited: Matt J on 14 Jul 2018
According to the Walter answer on above my problem solved easily using :
L(1) = plot(nan, nan, 'b-');
L(2) = plot(nan, nan, 'r--');
legend(L, {'first case', 'second case'})
  2 Comments
Matt J
Matt J on 14 Jul 2018
This gives an error,
Error using legend>process_inputs (line 554)
Invalid argument. Type 'help legend' for more information.
Error in legend>make_legend (line 306)
[autoupdate,orient,location,position,children,listen,strings,propargs] = process_inputs(ha,argin); %#ok
Error in legend (line 259)
make_legend(ha,args(arg:end),version);
Walter Roberson
Walter Roberson on 15 Jul 2018
Turns out you just need
hold on
to be in effect, as otherwise the second plot() clears the axes.

Sign in to comment.

More Answers (1)

Matt J
Matt J on 14 Jul 2018
Edited: Matt J on 14 Jul 2018
This might be what Walter meant,
t=linspace(0,1,10);
L(1:2) = plot(t,exp(-t), 'r--',nan,nan,'k--');hold on
L(3:4) = plot(t,1-exp(-t), 'g^-',nan,nan,'m^-'); hold off
legend(L([2,4]), 'Red','Green')
  2 Comments
Luiz Bacelar
Luiz Bacelar on 1 May 2020
how to solve this? I have similar problem
Walter Roberson
Walter Roberson on 1 May 2020
plot(nan,nan) with appropriate line style and color, once for each different thing you want to appear in the legend, recording the handle that is returned. Then when you call legend(), pass that array of handles in as the first parameter to legend()

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!