Sibbs Gambling
Sibbs Gambling

Reputation: 20345

Vectorize plotting multiple lines with different colors in MATLAB?

Is there a way to vectorize/accelerate the task of plotting multiple lines with different colors?

The working-but-slow approach is

X = [1 2; 3 4];
Y = [2 -4; 5 2];
figure;
hold on;
colors = [1 0 0; 0 1 0];
for idx = 1:size(X, 2)
    l = plot(X(:, idx), Y(:, idx), 'Color', colors(idx, :));
end
hold off;

I tried

X = [1 2; 3 4];
Y = [2 -4; 5 2];
figure;
plot(X, Y, 'Color', [1 0 0; 0 1 0]);

but no luck.

Upvotes: 2

Views: 90

Answers (1)

Luis Mendo
Luis Mendo

Reputation: 112659

This is probably too hacky to be a useful replacement of the loop, but here it goes:

set(gca, 'ColorOrder', [1 0 0; 0 1 0], 'NextPlot', 'add')
plot(X, Y);

The 'ColorOrder' property contains the colors to be used by default for new plots. Setting 'NextPlot' to 'add' seems to be necessary so that the call to plot doesn't reset 'ColorOrder' to its default value.

Tested on R2015b.

Upvotes: 2

Related Questions