同一行中的多种颜色

Multiple colors in the same line

我想在 Matlab 中绘制正弦曲线。但我希望正值是蓝色,负值是红色。

下面的代码只是让一切都变红了...

x = [];
y = [];
for i = -180 : 180
    x = [x i];
    y = [y sin(i*pi/180)];
end
p = plot(x, y)
set(p, 'Color', 'red')

绘制 2 条不同颜色的线,positive/negative 区域的 NaN

% Let's vectorise your code for efficiency too!
x = -pi:0.01:pi; % Linearly spaced x between -pi and pi
y = sin(x);      % Compute sine of x

bneg = y<0;      % Logical array of negative y

y_pos = y; y_pos(bneg) = NaN; % Array of only positive y
y_neg = y; y_neg(~bneg)= NaN; % Array of only negative y

figure; hold on; % Hold on for multiple plots
plot(x, y_neg, 'b'); % Blue for negative
plot(x, y_pos, 'r'); % Red for positive

输出:


注意:如果您对散点图感到满意,则不需要 NaN 值。他们只是为了打破界限,所以你不会在地区之间加入。你可以这样做

x = -pi:0.01:pi;
y = sin(x);
bneg = y<0;
figure; hold on;
plot(x(bneg), y(bneg), 'b.');
plot(x(~bneg), y(~bneg), 'r.');

输出:

这很清楚,因为我的观点只相差0.01。进一步间隔的点看起来更像散点图。