plot different color
Show older comments
Hi,
Let's say I have x = 1:100; y = sin(x); I wish to plot it in blue but if y is superior at 0.5, I want that the plot changes color for red.
Thx
Accepted Answer
More Answers (1)
Sven
on 16 Nov 2011
Steven, try this, it plots two separate plots depending on whether y is above/below 0.5:
x = 0:pi/20:10*pi; y = sin(x);
mask = y>0.5;
figure, plot(x(mask),y(mask),'r.', x(~mask),y(~mask),'b.')
Now, this plot kind of does what you said, but not what (I think) you intend. I think that you want the lines joined, and you want the line to change colour every time it crosses the y=0.5 axis. That's a little more tricky. We will need to first calculate the X-location of every crossing of the y=0.5 line using Doug Schwarz's very good intersections submission
[Xx,Yx Xinds] = intersections(x,y,x([1 end]),[0.5 0.5]);
We then make segments between each of the crossings:
xSegs = arrayfun(@(from,to)[Xx(from) x(ceil(Xinds(from)):floor(Xinds(to))) Xx(to)], 1:numXsecs-1, 2:numXsecs,'UniformOutput',false);
ySegs = arrayfun(@(from,to)[Yx(from) y(ceil(Xinds(from)):floor(Xinds(to))) Yx(to)], 1:numXsecs-1, 2:numXsecs,'UniformOutput',false);
Next we append the start and end segments:
xSegs = [{[x(1:floor(Xinds(1))) Xx(1)]} xSegs {[Xx(end) x(ceil(Xinds(end)):end)]}];
ySegs = [{[y(1:floor(Xinds(1))) Yx(1)]} ySegs {[Yx(end) y(ceil(Xinds(end)):end)]}];
Now we ask which of these segments should be red or blue?
highMask = cellfun(@max,ySegs)>0.5;
Now we plot each segment separately:
figure, hold on
cellfun(@(x,y)plot(x,y,'b'),xSegs(~highMask),ySegs(~highMask))
cellfun(@(x,y)plot(x,y,'r'),xSegs(highMask),ySegs(highMask))
Wow. That was more complicated than I expected. I'm sure there are different ways to do this. Note that I've included lots of cellfun() and arrayfun() code... if you're not familiar with those functions they can be a little daunting. Hope this helped.
Categories
Find more on Graphics Object Properties in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!