Plotting different color points based on array values
206 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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
0 commentaires
Réponse acceptée
William Rose
le 6 Mar 2023
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.
0 commentaires
Plus de réponses (2)
Les Beckham
le 6 Mar 2023
Modifié(e) : Les Beckham
le 6 Mar 2023
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
0 commentaires
Voss
le 6 Mar 2023
Modifié(e) : Voss
le 7 Mar 2023
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')
0 commentaires
Voir également
Catégories
En savoir plus sur Line Plots 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!