how to set a line with different color

2 次查看(过去 30 天)
I want to set a line obj with different color on different parts. But the following code is not work.
pl=line(nan,nan,'color','b','userdata',[]);
x1=[1:500];
y1=sin(0.2*x1);
x2=[501:1000];
y2=sin(0.2*x2);
set(pl,'xdata',x1,'ydata',y1,'color','r','xdata',x2,'ydata',y2,'color','k');
Is that possible to set a line object with different color on different part?

采纳的回答

Guillaume
Guillaume 2017-7-6
No, it is not possible to have a single line object with segments of different colour. You have to have a new line object for each segment as per KSSV's example. Note that plot will return the array of line objects which you can pass as one variable to the other code that will act on it. You may have to modify slightly that other code so it can cope with a non-scalar object but it shouldn't be too arduous. e.g.:
x = linspace(0, 2*pi, 1000);
hlines = plot(reshape(x, [], 4), reshape(sin(x), [], 4))
[hlines.LineWidth] = deal(2); %This is how to modify one of the property for all the lines at once
[hlines.LineStyle] = deal(':');
  2 个评论
yan zhang
yan zhang 2017-7-6
Thank you very much, you help me a lot!
Cloud1995
Cloud1995 2018-4-8
It is an awesome solution to my problem. Thanks so much!

请先登录,再进行评论。

更多回答(1 个)

KSSV
KSSV 2017-7-6
编辑:KSSV 2017-7-6
x1=[1:500];
y1=sin(0.2*x1);
x2=[501:1000];
y2=sin(0.2*x2);
figure
hold on
plot(x1,y1,'r')
plot(x2,y2,'b')
figure(2)
plot(x1,y1,'r',x2,y2,'b')
  6 个评论
KSSV
KSSV 2017-7-6
When you use set the previous plot is over written. You can straight away use line as I have shown.
yan zhang
yan zhang 2017-7-6
Thanks a lot. I should draw the line which will change every few seconds, and different colors represent different states. If a line obj can have different color, The code
set(pl,'ydata',y);
will meet my request. I will try other ways to solve the problem.
Thanks again.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 多边形 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!