Tell MATLAB not to update the next default color for a specific plot

Viewed 1059

Suppose the following case:

hold on 
plot(rand(1,20));
plot(rand(1,10));
plot(rand(1,20));

MATLAB will plot the 3 lines, each with a default color (e.g. red, blue, yellow).

Now, as the second plot is shorter, I want to do the following:

hold on 
plot(rand(1,20));
pl=plot(rand(1,10));
plot(11:20,rand(1,10),'color',get(pl,'color') ...
  ,'LineStyle','--'); 
plot(rand(1,20)); 

However while the 3rd plot does indeed have the color of the second plot, the 4th plot has the 4th default color, not the 3rd. It appears that MATLAB will update the index of the next default color order regardless if it is using it or not.

While I am aware that I can do get(groot,'DefaultAxesColorOrder') to get all the default colors and then set each of the plots properties to the index I want, I was wondering if there is a way of telling MATLAB "hey, for the next plot, do not update that default color index"

3 Answers

LuisMendo's comment works well, so I put it into a function:

function undoColorOrderUpdate(axis, steps)
    if ~exist('axis', 'var')
        axis = gca;
    end
    if ~exist('steps', 'var')
        steps = 1;
    end

    oldindex = get(axis, 'ColorOrderIndex');
    numcolors = size(get(axis, 'ColorOrder'),1);
    newindex = mod(oldindex-1-steps, numcolors)+1;
    set(axis, 'ColorOrderIndex', newindex);
end

You can then put undoColorOrderUpdate(); or undoColorOrderUpdate(gca, 1); before or after your to-be-ignored plot. If you put it before, you neither need to use a handle nor set the color manually anymore:

hold on;
plot(rand(1,20));
plot(rand(1,10));
undoColorOrderUpdate();
plot(11:20,rand(1,10),'LineStyle','--');
plot(rand(1,20));
Related