I want to draw a function f
given as 2 vectors: x
and y
, so y=f(x)
.
I use plot(x,y)
, but now I need it be blue above 0 and red under so it look like this:
How I can make each plot with different color (random)? With the code below, the plot limited to one color for all six vectors. plot(x,y,'-rs','LineWidth',1,... 'MarkerEdgeColor','k',... 'MarkerFaceColor','g',... 'MarkerSize',5); matlab.
Using RGB triplets to change colors One can specify colors using a vector that gives the RGB triple where in MATLAB, each of the three values are numbers from 0 to 1. Usually RGB colors have values from 0 to 255. You can use those numbers and divide the vector by 255 to use within MATLAB.
purple = [107 76 154]./255; cl_colors = {blue, red, black, ...
When you plot a vector in matlab, any segment of that vector that is filled with NaNs will not be plotted. So one trick to accomplish your goal is to plot a second line on top of the original one with the relevant segments removed using Nans. For example,
x = linspace(1,100,1000);
y = sin(x);
% Using a cutoff of y>=0.5
belowCutoff = y;
belowCutoff(y>=0) = NaN; % Replace points above cutoff with NaNs;
figure;
plot(x,y,'r',x, belowCutoff, 'b');
y0 = 0; % threshold
color1 = [1 0 0]; % below threshold
color2 = [0 0 1]; % above threshold
x = 1 : 10;
y = randn(1, 10);
threshold_plot(x, y, y0, color1, color2);
function threshold_plot(x, y, y0, color1, color2)
hold on;
n = length(x);
for i = 2 : n
x1 = x(i - 1); y1 = y(i - 1);
x2 = x(i); y2 = y(i);
ascending = y1 < y2;
if x1 == x2
if ascending
plot([x1 x2], [y1, y0], 'Color', color1);
plot([x1 x2], [y0, y2], 'Color', color2);
else
plot([x1 x2], [y1, y0], 'Color', color2);
plot([x1 x2], [y0, y2], 'Color', color1);
end;
elseif y1 == y2
if threshold <= y1
plot([x1 x2], [y1 y2], 'Color', color2);
else
plot([x1 x2], [y1 y2], 'Color', color1);
end;
else
a = (y2 - y1) / (x2 - x1);
b = y1 - a * x1;
x0 = (y0 - b) / a;
if x1 <= x0 && x0 <= x2
if ascending
plot([x1 x0], [y1, y0], 'Color', color1);
plot([x0 x2], [y0, y2], 'Color', color2);
else
plot([x1 x0], [y1, y0], 'Color', color2);
plot([x0 x2], [y0, y2], 'Color', color1);
end;
else
if y0 <= y1
plot([x1 x2], [y1 y2], 'Color', color2);
else
plot([x1 x2], [y1 y2], 'Color', color1);
end;
end;
end;
end;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With