Q:

legend for group of lines

I like to plot two groups of lines in the same plot. Each group has two lines with same color and I have to draw them in the order of one group after another group. I try to show legend for groups only not for lines. How can I do this? Here is a simplification of my wrong code:
plot(x1, y1, color1); hold on;
plot(x2, y2, color1); hold on;

plot(x3, y3, color2); hold on;
plot(x4, y4, color2); hold on;

legend({color1, color2})

Thanks!

UPDATE:
A new question, is there any way to write legend after each line and without overwriting the previous legend but append to it? i.e. something similar to "hold on" but applied to legend.

A:

There are a few ways you can do this. The easiest way is to get the handle for the first plotted line of each group and pass that as the first argument to LEGEND:
h1 = plot(x1, y1, color1);
hold on;
plot(x2, y2, color1);

h2 = plot(x3, y3, color2);
plot(x4, y4, color2);

legend([h1 h2],{'label1', 'label2'});

A:

You can stitch multiple lines together using NaN, which means "pick up the pen". Then the legend will treat each as a single set of data.
hold on
plot([x1 NaN x2], [y1 NaN y2], 'b');
plot([x3 NaN x4], [y3 NaN y4], 'r');
legend({'foo', 'bar'})
hold off

For convenience, you can stick this in the multi-line version of plot.
plot([x1 NaN x2], [y1 NaN y2], 'b', [x3 NaN x4], [y3 NaN y4], 'r');

This could let you set() properties for the grouped lines as units, too.

A:

In response to your update, and to extend Andrew Janke's answer, I found this method to be perfect for an automatic legend:
% Sample data
order = -1:2;      % number of orders to plot
x = (0:0.01:10)';

% Plot each instance of data in a separate graph
for i=1:numel(order)
    plot(x,besselj(order(i),x))
    hold all

    % Amend legend to include new plot
    [~,~,~,current_entries] = legend;
    legend([current_entries {sprintf('Order = %i',order(i))}]);
end

Gives the following figure:

EDIT: In Matlab 2014b, the use of "legend" has changed and the solution(s) above will throw errors. Instead, we should modify the 'String' property of the legend. Follow this code to get the same result as my previous example:
% Sample data
order = -1:2;      % number of orders to plot
x = (0:0.01:10)';

% Plot each instance of data in a separate graph
for i=1:numel(order)
    plot(x,besselj(order(i),x))
    hold on

    % Amend legend 'entries' to include new plot
    entries(i) = { sprintf('Order = %i',order(i)) };
end

% Create legend using the 'entries' strings
legend('String',entries);

Now you can add as many plots as you want and the legend will automatically update!

