如何在保持相同颜色的同时循环使用 Octave 中的线条样式?

How to cycle through line styles in Octave while keeping same color?

我的目标是在同一个图形上绘制 2 个不同的主要函数,但也能够在那些与原始 2 个函数如何演变相关的相似函数之上绘制。例如,第一个函数将是红色和实心的,其后续的类似函数将是相同的颜色但循环使用不同的线型,同样对于第二个函数它们都是蓝色的但也会循环使用线型。这是一些示例代码:

lstyle = {" '-' ", " '--' ", " ':' ", " '-.' "};
i=1;

%Plot:
for n=1:3
  choose_lstyle = lstyle{i};
  y1 = (z.*n).^2;
  y2 = (z.*n).^3;
  plot(z,y1,'r','linestyle',choose_lstyle);
  plot(z,y2,'b','linestyle',choose_lstyle);
  n++;
  if i < length(lstyle) %cycle through line styles
    i = i+1;
    else
    i = 1;
  end
  hold on;
end

我正在尝试将“-”或“:”引号放在 choose_lstyle 所在的位置。基本上,如果你只有一种线型,它在引号中,它就像你会有的一样,除了我试图循环线型。

我在 运行 时得到的错误是:

error: set: invalid value for radio property "linestyle" (value =  '-' )
error: called from
__line__ at line 120 column 16
line at line 56 column 8
__plt__>__plt2vv__ at line 500 column 10
__plt__>__plt2__ at line 246 column 14
__plt__ at line 113 column 17
plot at line 220 column 10
PROGRAM_NAME at line 37 column 3
enter code here

你在那里有几个错误,这是一个有效的代码:

lstyle = {'-','--',':','-.'};
z = 1:100;

%Plot:
k = 1;
for n = 1:10
    y1 = (z.*n).^2;
    y2 = (z.*n).^2.1; % I changed it from 3 so you can see the red lines
    plot(z,y1,'r',z,y2,'b','linestyle',lstyle{k});
    if k < length(lstyle) %cycle through line styles
        k = k+1;
    else
        k = 1;
    end
    hold on;
end

如有不明之处欢迎在评论中提出。


这段代码会给你类似的结果,但它更紧​​凑、更高效:

lstyle = {'-','--',':','-.'};
z = 1:10;
by = bsxfun(@times,z.',1:10).^2;
ry = bsxfun(@times,z.',1:10).^2.1;
p = plot(z,ry,'r',z,by,'b');
k = 1;
for n = 1:numel(p)
    p(n).LineStyle = lstyle{k};
    k = k+1;
    if k > numel(lstyle)
        k = 1;
    end   
end

如果你的MATLAB版本是2014之前的,或者你只是想找一个简洁的代码,你也可以这样写:

lstyle = {'-','--',':','-.'};
z = 1:10;
by = bsxfun(@times,z.',1:10).^2;
br = bsxfun(@times,z.',1:10).^2.1;
p = plot(z,br,'r',z,by,'b');
lineStyles = repmat(lstyle,1,ceil(numel(p)/numel(lstyle)));
set(p,{'LineStyle'},lineStyles(1:numel(p)).');