5
我想畫一個函數f
給出2個向量:x
和y
,所以y=f(x)
。 我用plot(x,y)
,但現在我需要它是藍大於0和紅色下所以它看起來像這樣:Matlab雙色圖
我想畫一個函數f
給出2個向量:x
和y
,所以y=f(x)
。 我用plot(x,y)
,但現在我需要它是藍大於0和紅色下所以它看起來像這樣:Matlab雙色圖
當您繪製在MATLAB中的向量,是充滿NaN的是矢量的任何部分將不會被繪製。因此,實現您的目標的一個訣竅就是在原始頂點上繪製第二行,並使用Nans移除相關的片段。例如,
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;
上有MathWorks的文件交換網站這個腳本調用有條件的彩色線圖http://www.mathworks.co。英國/ matlabcentral/fileexchange/30423-有條件色線積 – KatyB