【问题标题】:MATLAB - plot multiple unconnected lines with patch and specify linecolorMATLAB - 用补丁绘制多条未连接的线并指定线条颜色
【发布时间】:2017-10-26 13:22:11
【问题描述】:

我想使用 patch 在一个命令中绘制多个未连接的行。这些线条具有我要指定的不同颜色。不幸的是,补丁在黄色到蓝色区域使用随机颜色而不是我定义的颜色 - 我该如何解决这个问题?

clear all
close all
cla;

x=[];
y=[];
CC=[];
n=10;
for i=1:n
    % define start and end from i-th line
    x(end+1)=i;
    x(end+1)=i+1;
    % add nan to seperate lines
    x(end+1)=nan;

    % define start and end from i-th line
    y(end+1)=i;
    y(end+1)=1;
    % add nan to seperate lines
    y(end+1)=nan;

    CC(end+1,1:3)=0.1.*i;
end

%funktioniert
figure(1)
subplot(1,2,1)
h = patch(x', y', 0);
set(h,'LineWidth',2);
set(h,'cdata', CC, 'edgecolor','flat','facecolor','none')
title('wrong colors')

subplot(1,2,2)
for i=1:n
    xx=[1:3];
    yy=[i i i];
    line(xx,yy,'Color',CC(i,:))
    hold on
end
title('wanted colors')

非常感谢! smaica

【问题讨论】:

  • 你为什么用patch画线?这段代码似乎过于笨拙...
  • 我发现可以在一个命令中以不同颜色绘制多条线。如果您能帮助我提供其他解决方案,我将不胜感激!
  • 对于寻找单线绘图的人来说,实际设置数据是非常浪费的!初始化xy 就像x = reshape([1:n; 2:n+1; NaN(1,n)], 1, []); y = reshape([1:n; ones(1,n), NaN(1,n)], 1, []) 然后使用短循环和line 看起来还不错。
  • 这只是一个例子。我的实际代码在更新模拟中绘制了 >100000 行,并且不会花费超过最大值。 1秒。所以循环不起作用。

标签: matlab colors patch


【解决方案1】:

如果要绘制线条,请使用专用于此目的的函数plotline,而不是使用patch。只需将'ColorOrder' 更改为您想要的颜色即可。

n = 10;
%Starting and ending point of lines in each col of x and y
x = [1:n; 2:n+1];    
y = [1:n; ones(1,n)]; 
CC = repmat(0.1:0.1:1,3,1).';   %Required colors
%Changing ColorOrder to required colors ( and turning the box (optional) )
set(gca, 'ColorOrder', CC, 'box', 'on');
line(x,y);    %or plot(x,y)

结果:

【讨论】:

  • 另外值得注意的是,由于 OP 对速度感兴趣,因此该解决方案将相对较快,因为 line 是一种更原始​​的方法。
  • 非常感谢,效果很好。现在我唯一的问题是,当我定义线图的句柄时,我无法使用与 Matlab 相同的命令更改它们的颜色:“使用 set 时出错 Line 类上没有 ColorOrder 属性。”。我的代码是:h(:,k)=line(x,y); set(h(:,k),'ColorOrder', CC, 'box', 'on');
  • 'ColorOrder' 是轴的属性,而不是线。使用您提到的方法(似乎是一个循环),您实际想要更改的属性是Color,而不是ColorOrder。见Line Properties
  • @SardarUsama 谢谢,但h(:,k) = line(nodesx',nodesy'); set(h(:,k), 'Color', colors, 'box', 'on','LineWidth',M); 不再起作用:Color value must be a 3 element vector
  • @aciams 您在一次迭代中绘制了多少行?您不能使用'Color' 属性为多行设置不同的颜色。而且你不需要在这里循环。如答案所示,您可以一次绘制所有线条。顺便说一句,box 是轴的属性,而不是线的属性。与此无关。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-19
  • 1970-01-01
相关资源
最近更新 更多