plot different color
7 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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
0 commentaires
Réponse acceptée
Kelly Kearney
le 16 Nov 2011
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).
0 commentaires
Plus de réponses (1)
Sven
le 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.
0 commentaires
Voir également
Catégories
En savoir plus sur Data Distribution Plots dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!