plot different color

조회 수: 32 (최근 30일)
Steven
Steven 2011년 11월 16일
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

채택된 답변

Kelly Kearney
Kelly Kearney 2011년 11월 16일
Another way of doing this would be to use a patch object instead of a line; that way you can get a color-change effect with only one object, and don't need to figure out the change points manually.
x = 0:pi/20:10*pi;
y = sin(x);
c = sign(y - 0.5);
p = patch([x NaN], [y NaN], [c NaN], [c NaN], 'edgecolor', 'interp');
colormap([0 0 1; 1 0 0]);
Note that you may need to increase the number of points defining your line in order to get a relatively narrow color transition zone (for example, in your original example with x = 1:100, the coarseness of the plot is not ideal for this technique).

추가 답변 (1개)

Sven
Sven 2011년 11월 16일
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.

카테고리

Help CenterFile Exchange에서 Surface and Mesh Plots에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by