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

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

Respuestas (2)

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

4 comentarios

Thank you for your response sir. But i want a continuos curve, the problem with this is that this code does not give any continuos line, where I can see that above 0 it is red and below 0 it is green. I want a continuos line. Thank you.
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;
I have attached the data cc.mat.
x = 1:731;
load cc.mat
lev = 0;
aboveline = (cc >= lev);
bottomline = cc;
topline = cc;
bottomline(aboveline) = NaN;
topline(~aboveline) = NaN;
figure
plot(bottomline,'r');
hold on;
plot(topline,'g')
I have written the above code with the help of internet. But still did'nt get a continuos line
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');

Iniciar sesión para comentar.

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;

Categorías

Más información sobre Creating and Concatenating Matrices en Centro de ayuda y File Exchange.

Etiquetas

Preguntada:

el 16 de Feb. de 2022

Comentada:

el 16 de Feb. de 2022

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by