MATLAB: Plot different color

colorplot

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

Best Answer

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).