how to set a line with different color
2 views (last 30 days)
Show older comments
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?
0 Comments
Accepted Answer
Guillaume
on 6 Jul 2017
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 Comments
More Answers (1)
KSSV
on 6 Jul 2017
Edited: KSSV
on 6 Jul 2017
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 Comments
KSSV
on 6 Jul 2017
When you use set the previous plot is over written. You can straight away use line as I have shown.
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!