Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
585 views
in Technique[技术] by (71.8m points)

matlab - Multiple colors in the same line

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')
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

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:

output2

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...