Ploting same y axis with two colors

Assuming there is matrix 10x2, which is called HW. First collumn values will be the X axis. Second collumn is [1,4,5,7,2,24,8,9,18,11] and will be in Y axis. In the plot, higher y values than average will be in different color than lower y values. I wrote this code which does not work due to numbers does not match and I am unable to find a proper plot function. I cannot use programming (such as: if statements). By the way X also randomly distributed.
I need them in one line. Such as from 1 to 2 (first 5 element) line is red than to 6th element, 24, blue and goes like this (r,b,r,b)
HWT = find(HW(:,1)>=mean(HW(:,1)))
HWS = find(HW(:,1)<=mean(HW(:,1)))
plot(HW(:,1),HW(HWT,2),"Color","r",HW(HWS,2),"Color","b")
Is there any plot function to solve this.
Thank you for your help.

 Accepted Answer

HW = [rand(10,1) [1;4;5;7;2;24;8;9;18;11]];
%Mean value
m = mean(HW(:,2));
%Comparison with mean
idx1 = HW(:,2) >= m;
idx2 = ~idx1;
%Use the indices to plot the corresponding values
plot(HW(idx1,1), HW(idx1,2), 'r', HW(idx2,1), HW(idx2,2), 'b')
%Showing the average value
yline(m, 'k')

7 Comments

Gökberk Kaya
Gökberk Kaya on 23 Oct 2023
Edited: Gökberk Kaya on 23 Oct 2023
Thank you first of all,
But I need them in one line. Such as from 1 to 2 (first 5 element) line is red than blue to, 6th element, 24 and goes like this (r,b,r,b)
Dyuman Joshi
Dyuman Joshi on 23 Oct 2023
Edited: Dyuman Joshi on 23 Oct 2023
In that case, what should be the color of the line joining adjacent values which are on the different side of the mean?
E.g. - 5th element i.e. 2 is lower than the mean, and 6th element i.e 24 is higher than the mean. What should be the color of the line connecting these two points?
Simiarly for 24 and 8 as well.
If it is going to pass the mean, the destination's color will be the line's color. For an example, for 2 to 24, 24 is the destination therefore line will be blue but for the 24 to 8 case, 8 is the destination, so red.
Coloring the plot according to the value of the point compared to mean.
I hope you can use a for loop.
HW = [rand(10,1) [1;4;5;7;2;24;8;9;18;11]];
s = size(HW,1);
m = mean(HW(:,2));
color = ['rb'];
figure
hold on
for k=1:s-1
%Using indexing to assign color according to the comparison
idx = (HW(k+1,2)>m) + 1;
plot([k k+1], HW(k:k+1,2), color(idx));
end
hold off
yline(m)
Yes, Thank you for your help.
You are welcome :)

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!