Multiple colors in the same line

2019-01-15 21:12发布

问题:

I would like to plot a sine curve in Matlab. But I want it blue for the positive values and red for the negative values.

The following code just makes everything red...

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

回答1:

Plot 2 lines with different colours, and NaN values at the positive/negative regions

% 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

Output:


Note: If you're happy with scatter plots, you don't need the NaN values. They just act to break the line so you don't get join-ups between regions. You could just do

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

Output:

This is so clear because my points are only 0.01 apart. Further spaced points would appear more like a scatter plot.