How do I plot an indeterminate number of lines?

2 views (last 30 days)
I have a common problem where I need to plot a number of lines n, but I don't know how many there will be.
If I am making a series of lines I can do it with a matrix, then just do this:
plot(x scale, y(1), x scale, y(2),...,x scale, y(n))
The problem is that I don't always know what n will be, so I have to do it like this:
for i=1:1:n
plot(x scale, y(i))
The problem is that then the lines are all blue (I'd like the colors to cycle) and I can't make a legend.
Does anyone know how to solve this problem?
  1 Comment
Walter Roberson
Walter Roberson on 19 Jul 2012
Are those y(1) y(2) and so on all scalar values? So you are plotting a series of horizontal lines ? Or is y(1) y(2) really y{1} y{2} etc., cell array entries?

Sign in to comment.

Answers (2)

Walter Roberson
Walter Roberson on 19 Jul 2012
hold all holds the graph and the current line color and line style so that subsequent plotting commands do not reset the ColorOrder and LineStyleOrder property values to the beginning of the list. Plotting commands continue cycling through the predefined colors and line styles from where the last graph stopped in the list.

Jan
Jan on 19 Jul 2012
n = 32;
map = jet(16);
lineH = zeros(n, 1);
legendC = cell(n, 1);
axes('NextPlot', 'add'); % Equivalent to "hold on"
for i = 1:n
color = map(rem(i, 16) + 1, :);
lineH(i) = line(1:10, rand(1, 10), 'Color', color);
legendC{i} = sprintf('Line %d', i);
end
legend(lineH, legendC);
I cannot debug this currently. The low-level function line is faster than the high-level function plot.

Categories

Find more on 2-D and 3-D Plots in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!