Line plot with two different color based on the condition of the value
4 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
回答(2 个)
Benjamin Thompson
2022-2-16
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 个评论
Benjamin Thompson
2022-2-16
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
2022-2-16
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;
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Annotations 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!