Plotting different color points based on array values

206 次查看(过去 30 天)
I have an array and I want to plot it applying different colors depending on the values. If the value to be plotted is below a threshol the color is green, if above it should be red. All data should be connected by straight line.
Whit the code here I can only display values below the threshold.
How can I display all the values?
length1=length(DE);
for i=1:length(DE)
if DE(i)>=5
color='or';
else
color='og';
plot(data.Name_1(i),DE(i),color)
end
hold on
end

采纳的回答

William Rose
William Rose 2023-3-6
One way:
x=1:100;
N=length(x);
DE=10*rand(1,N);
c=zeros(N,3); %allocate colors
for i=1:N, if DE(i)>5, c(i,:)=[1,0,0]; else c(i,:)=[0,1,0]; end, end
subplot(211); scatter(x,DE,50,c,'filled'); hold on
plot(x,DE,'-k'); hold off %add line connecting the points, as you requested
Another way:
clear
x=1:100;
DE=10*rand(size(x));
subplot(212); scatter(x(DE<5),DE(DE<5),'g','filled');
hold on
scatter(x(DE>=5),DE(DE>=5),'r','filled');
plot(x,DE,'-k'); %add straight lines between points
Try it. Good luck.

更多回答(2 个)

Les Beckham
Les Beckham 2023-3-6
编辑:Les Beckham 2023-3-6
x = linspace(0, 10);
y = sin(x); % test data
yhi = y;
ylo = y;
threshold = 0.5;
idxlo = y <= threshold;
idxhi = y > threshold;
yhi(idxlo) = nan;
ylo(idxhi) = nan;
plot(x, yhi, 'ro-', x, ylo, 'go-')
grid on

Voss
Voss 2023-3-6
编辑:Voss 2023-3-7
data = struct('Name_1',randperm(50));
DE = 2.5+5*rand(1,50);
threshold = 5;
[~,idx] = sort(data.Name_1);
x = data.Name_1(idx);
y = DE(idx);
xy = [x(:) y(:)];
direction = diff(xy(:,2) > threshold);
do_interp_up = [direction == 1; false];
do_interp_down = [direction == -1; false];
do_interp = do_interp_up | do_interp_down;
N = size(xy,1);
new_xy = NaN(N+3*nnz(do_interp),2);
jj = 1;
for ii = 1:N
new_xy(jj,:) = xy(ii,:);
if do_interp(ii)
new_xy(jj+[1 3],1) = interp1(xy(ii+[0 1],2),xy(ii+[0 1],1),threshold);
new_xy(jj+2,2) = threshold;
if do_interp_up(ii)
new_xy(jj+[1 3],2) = threshold+[-1 1]*eps(threshold);
else
new_xy(jj+[1 3],2) = threshold+[1 -1]*eps(threshold);
end
jj = jj+3;
end
jj = jj+1;
end
low_idx = new_xy(:,2) <= threshold;
high_idx = new_xy(:,2) >= threshold;
hold on
plot(new_xy(low_idx,1),new_xy(low_idx,2),'g')
plot(new_xy(high_idx,1),new_xy(high_idx,2),'r')

类别

Help CenterFile Exchange 中查找有关 Line Plots 的更多信息

标签

产品


版本

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by