Is there a way to make a plot of a line with different colors?

If I have y = rand(100,1), can I plot y such that the portions of the line that are greater than or equal to 0.5 is plot in red while portions lying below 0.5 is plot in black?

 Accepted Answer

To plot lines as well:
% some data
x = linspace(0,1,100);
y = rand(1,length(x));
tf = y >= 0.5 ;
y2 = y ; y2(~tf) = nan ;
ph = plot(x,y,'k.-',x,y2,'ro-')
set(ph(2),'linewidth',2)

3 Comments

Thanks for the responses but none of them provide what I am hoping to achieve. I have attached an image of what I am trying to accomplish. The dotted line in the image would be the 0.5 line. All parts of the curve above 0.5 should be in red; parts of the curve below the 0.5 line should be in black.
I'm not seeing the attachment. Where did you attach it????
Sorry. I thought that I had also submitted the attachment. I am re-submitting.
FYI, I went ahead and used the last lines of code that Jos provided but made an edit to it. Here is what I now have and this one seems to be working:
% some data
x = linspace(0,1,100);
y = rand(1,length(x));
x1 = linspace(0,1,5000);
y1 = interp1(x,y,x1);
tf = y1 >= 0.5 ;
y2 = y1 ; y2(~tf) = nan ;
ph = plot(x1,y1,'k.-',x1,y2,'ro-')
set(ph(2),'linewidth',2)

Sign in to comment.

More Answers (0)

Categories

Community Treasure Hunt

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

Start Hunting!