Plot with 'SeriesIndex' set to 1 forces all lines in the plot call to have the same color and not iterate the color order

27 views (last 30 days)
matrix=linspace(0,1,100)'*[1:4];
matrix2=linspace(0,1,102)'*(0.5+[1:4]);
figure; plot(matrix); hold on; plot(matrix2,'--') % try1
figure; plot(matrix); hold on; plot(matrix2,'--','SeriesIndex',1) % try2
For plot(matrix) automatically 4 lines are drawn with 4 distinct colors.
By using #try1
I get 8 lines with 7 distintc colors.
However, I would like to get matrix2 use the same colors as matrix 1 (since they indicate same physical meaning).
By using #try2
I get all lines of matrix2 just turned into blue.
IS there a simple way (e.g. not requiring to know in advance how many lines will be plotted, and how many plots are required following the hold on - so it should be automatic) to do that? I thought that 'SeriesIndex',1 should have handled that, but I guess I missunderstood its functionality.

Accepted Answer

Amichai Sanderovich
Amichai Sanderovich on 8 Jan 2023
Hi,
Thank you for the suggestion. It seems to do the work indeed.
However, I found a solution with a lower line count:
set(gca,'ColorOrderIndex',1);
before each plot command.
which does the same.

More Answers (1)

Voss
Voss on 5 Jan 2023
Edited: Voss on 5 Jan 2023
matrix=linspace(0,1,100)'*[1:4];
matrix2=linspace(0,1,102)'*(0.5+[1:4]);
figure;
h1=plot(matrix);
hold on;
h2=plot(matrix2,'--');
set(h2,{'Color'},get(h1,'Color'))
  3 Comments
Voss
Voss on 5 Jan 2023
It won't work if h1 and h2 are not the same size (i.e., numel(h1) ~= numel(h2)), but you can adjust it to handle that:
matrix=linspace(0,1,100)'*[1:6];
matrix2=linspace(0,1,102)'*(0.5+[1:4]);
figure;
h1=plot(matrix);
hold on;
h2=plot(matrix2,'--');
nh1 = numel(h1);
nh2 = numel(h2);
c = get(h1,'Color');
if nh2 <= nh1
% set the colors of h2 to be the first nh2 colors of c
set(h2,{'Color'},c(1:nh2))
else
% set the colors of the first nh1 lines in h2 to c
set(h2(1:nh1),{'Color'},c)
end

Sign in to comment.

Categories

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

Products


Release

R2022a

Community Treasure Hunt

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

Start Hunting!