0
votes

I want to plot four curves in a single figure from matlab, so I am using hold on. Furthermore, I want to create an legend to each curve, so I wrote the code:

clear all
x=linspace(0,10,100);
x2=linspace(-5,15,100);
x3=linspace(-10,20,100);
x4=linspace(35,40,100);

figure(1)

plot(x,x2)

legend('x2')
hold on 

plot(x,x3)

legend('x3')
hold on

plot(x,x4)

legend('x4')
hold on

plot(x,x)

legend('x')

hold off

But the result is that all my curves are in the same color, and just the last legend "x" has appeared in the figure (see it below).

enter image description here

How can I set one legend to each curve? All curves must have different colors.

2

2 Answers

1
votes

This depends a bit on your matlab version. In older versions (and in octave), plots added through the use of hold on get the same color. In R2015b (i don't know when this was introduced), the individual plots get different colors, but still only one legend is displayed. Plots using Matlab R2015b

To get multiple colors and multiple legend entries, you can specify all data to be plotted in one call, the same for the legends:

plot(x, x, x, x2, x, x3, x, x4);

or

plot(x, [x', x2', x3', x4']);

For the legends, approach the same way:

legend('x', 'x2', 'x3', 'x4');

enter image description here

0
votes

If you want to build up a legend without knowing the number of entries before hand, you would want to search for "dynamic legends". See for example here: http://undocumentedmatlab.com/blog/legend-semi-documented-feature