how to set a line with different color

2 visualizzazioni (ultimi 30 giorni)
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?

Risposta accettata

Guillaume
Guillaume il 6 Lug 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 Commenti
yan zhang
yan zhang il 6 Lug 2017
Thank you very much, you help me a lot!
Cloud1995
Cloud1995 il 8 Apr 2018
It is an awesome solution to my problem. Thanks so much!

Accedi per commentare.

Più risposte (1)

KSSV
KSSV il 6 Lug 2017
Modificato: KSSV il 6 Lug 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 Commenti
KSSV
KSSV il 6 Lug 2017
When you use set the previous plot is over written. You can straight away use line as I have shown.
yan zhang
yan zhang il 6 Lug 2017
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.

Accedi per commentare.

Tag

Community Treasure Hunt

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

Start Hunting!