重置用于在 Matlab / Octave 中绘图的 ColorOrder 索引

Reset ColorOrder index for plotting in Matlab / Octave

我有矩阵 x1, x2, ... 包含 可变 个行向量。 我做连续的情节

figure
hold all % or hold on
plot(x1')
plot(x2')
plot(x3')

Matlab 或 Octave 通常遍历 ColorOrder 并以不同颜色绘制每条线。 但我希望每个 plot 命令再次从 colororder 中的第一个颜色开始,所以在默认情况下,矩阵中的第一个向量应该是蓝色,第二个是绿色,第三个是红色等等

不幸的是,我找不到任何与颜色索引相关的 属性,也找不到其他重置它的方法。

found a link 一个人最终解决了这个问题。他使用此代码:

t = linspace(0,1,lineCount)';
s = 1/2 + zeros(lineCount,1);
v = 0.8*ones(lineCount,1);
lineColors = colormap(squeeze(hsv2rgb(t,s,v)))
ax=gca
ax.ColorOrder = lineColors;

假设您的每个矩阵都具有相同的行数,这应该对您有用。如果他们不这样做,那么我有一种感觉,您将不得不使用上面的 lineColors 分别循环和绘制每条线,以便为 'Color' linespec 属性 指定一个 RBG 三元组plot。所以你可以使用这样的函数:

function h = plot_colors(X, lineCount, varargin)

    %// For more control - move these four lines outside of the function and make replace lineCount as a parameter with lineColors
    t = linspace(0,1,lineCount)';                              %//'
    s = 1/2 + zeros(lineCount,1);
    v = 0.8*ones(lineCount,1);
    lineColors = colormap(squeeze(hsv2rgb(t,s,v)));


    for row = 1:size(X,1)
        h = plot(X(row, :), 'Color', lineColors(row,:), varargin{:}); %// Assuming I've remembered how to use it correctly, varargin should mean you can still pass in all the normal plot parameters like line width and '-' etc
        hold on;
    end

end

其中 lineCount 是您的 x 矩阵中最大的行数

定义一个函数,拦截对 plot 的调用,并在执行实际绘图之前将 'ColorOrderIndex' 设置为 1

function plot(varargin)
if strcmp(class(varargin{1}), 'matlab.graphics.axis.Axes')
    h = varargin{1}; %// axes are specified
else
    h = gca; %// axes are not specified: use current axes
end
set(h, 'ColorOrderIndex', 1) %// reset color index
builtin('plot', (varargin{:})) %// call builtin plot function

我已经在 Matlab R2014b 中测试过了。

您可以在当前坐标轴上移动原始 ColorOrder,以便新绘图从相同颜色开始:

h=plot(x1');
set(gca, 'ColorOrder', circshift(get(gca, 'ColorOrder'), numel(h)))
plot(x2');

您可以将其包装在一个函数中:

function h=plotc(X, varargin)
h=plot(X, varargin{:});
set(gca, 'ColorOrder', circshift(get(gca, 'ColorOrder'), numel(h)));
if nargout==0,
    clear h
end
end

并致电

hold all
plotc(x1')
plotc(x2')
plotc(x3')

如果您想要一种稍微老套的、最少代码行的方法,也许您可​​以在每个矩阵图的末尾绘制适当数量的 (0,0) 点,以将您的颜色顺序推回到开头 - 它是像 Mohsen Nosratinia 的解决方案,但不太优雅...

假设有七种颜色可以循环,就像在 matlab 中一样,您可以这样做

% number of colours in ColorOrder
nco = 7;
% plot matrix 1
plot(x1');
% work out how many empty plots are needed and plot them
nep = nco - mod(size(x1,1), nco); plot(zeros(nep,nep));
% plot matrix 2
plot(x2');
...
% cover up the coloured dots with a black one at the end
plot(0,0,'k');

从 R2014b 开始,有一种简单的方法可以重新开始您的颜色顺序。

每次需要重置颜色顺序时插入此行。

set(gca,'ColorOrderIndex',1)

ax = gca;
ax.ColorOrderIndex = 1;

见: http://au.mathworks.com/help/matlab/graphics_transition/why-are-plot-lines-different-colors.html