# Line plot with two different color based on the condition of the value

3 views (last 30 days)
SWARNENDU PAL on 16 Feb 2022
Commented: Benjamin Thompson on 16 Feb 2022
I have a array of 731 numbers. Some have value greater than 0 and some have value less than 0. I want to draw a plot based on the condition, if the value is greater than 0 the color of the line will be red and if the value is less than 0 the color of the line will be green. I have attached the .mat file.Thank you

Benjamin Thompson on 16 Feb 2022
One way is to use index vectors. But you may not want the points connected by lines that cross subsets of the other color. If you really want the line you would need to do some more processing of this output, maybe a for loop that plots red and then green groups. This example below shows how to get the index vectors and then plot the data points with no lines.
>> t = 0:0.01:5;
>> x = 2*sin(2*pi*50/33*t);
>> Ired = x >= 0;
>> Igreen = x < 0;
>> figure, plot(t(Ired), x(Ired), 'ro', t(Igreen), x(Igreen), 'gx');
Benjamin Thompson on 16 Feb 2022
If you just one to draw lines connecting the gaps in each of the two data sets, you do not need to add NaN. Just plot the data where the index vector is one. You need one more index vector "n" that keeps the data in the original location when you plot it:
n = 1:length(cc);
figure, plot(n(aboveline), topline(aboveline), 'r');

Benjamin Thompson on 16 Feb 2022
Try to use this example to produce the results you want. If you have further problems then ask a specific question and post your data and sample code. As I suggested, a for loop is probably needed to plot groups of red and green data sets one by one.
One way to quickly identify the red/green changes is with another index vector:
Ichange = diff(Ired) ~= 0;