同一行中有多种颜色 [英] Multiple colors in the same line

查看:93
本文介绍了同一行中有多种颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Matlab中绘制正弦曲线.但是我希望它的蓝色代表正值,红色代表负值.

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

推荐答案

绘制2种颜色不同的行,并在正/负区域绘制NaN

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

输出:

注意:如果您对散点图满意,则不需要NaN值.他们只是打破界限,所以您不会在区域之间结成联盟.你可以做

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

输出:

这很清楚,因为我的观点仅相隔0.01.进一步隔开的点看起来更像是散点图.

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

这篇关于同一行中有多种颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆