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

7 vues (au cours des 30 derniers jours)
SWARNENDU PAL
SWARNENDU PAL le 16 Fév 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

Réponses (2)

Benjamin Thompson
Benjamin Thompson le 16 Fév 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');
  4 commentaires
SWARNENDU PAL
SWARNENDU PAL le 16 Fév 2022
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
Benjamin Thompson
Benjamin Thompson le 16 Fév 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');

Connectez-vous pour commenter.


Benjamin Thompson
Benjamin Thompson le 16 Fév 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;

Catégories

En savoir plus sur Spline Postprocessing dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by