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

4 views (last 30 days)
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

Jos (10584)
Jos (10584) on 17 Feb 2014
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
Floyd Haylock
Floyd Haylock on 17 Feb 2014
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)

Community Treasure Hunt

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

Start Hunting!