Adding different colors to the same plotting line
16 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Hermes Chirino
le 4 Déc 2018
Modifié(e) : Adam Danz
le 25 Juin 2023
Hi MATLAB community, I am trying to add different colors to the same plot line. I want a color for 0<x<100, another color for 100<x<150, and another color for 150<x<200. Here is my code:
clear
clc
dx = 200/1000;
x = 0:dx:200;
for k = 1:length(x)
if x(k) <= 100
y(k) = sqrt(x(k));
end
if x(k) >100 && x(k)<=150
y(k) = (2*x(k))-190;
end
if x(k) > 150
y(k)=110;
end
end
plot(x,y,'color',rand(1,3),'DisplayName', '\surd(x)')
legend('-DynamicLegend')
hold all
plot(x,y,'color',rand(1,3),'DisplayName', '2x')
plot(x,y,'color',rand(1,3),'DisplayName', 'Constant')
xlabel('x'), ylabel('y')
0 commentaires
Réponse acceptée
Adam Danz
le 4 Déc 2018
Modifié(e) : Adam Danz
le 25 Juin 2023
The variables idx1, idx2, idx3 replace your for-loop and mark the indices of x and y that are categorized by your logical expressions. You can use them to calculate Y and to plot the 3 portions of the line with different colors.
clear
clc
dx = 200/1000;
x = 0:dx:200;
idx1 = x <= 100;
idx2 = x > 100 & x <= 150;
idx3 = x > 150;
y = nan(size(x));
y(idx1) = sqrt(x(idx1));
y(idx2) = (2.*x(idx2))-190;
y(idx3) = 110;
plot(x(idx1),y(idx1),'color',rand(1,3),'DisplayName', '\surd(x)')
legend('-DynamicLegend','Location','NorthWest')
hold all
plot(x(idx2),y(idx2),'color',rand(1,3),'DisplayName', '2x')
plot(x(idx3),y(idx3),'color',rand(1,3),'DisplayName', 'Constant')
xlabel('x'), ylabel('y')
2 commentaires
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Labels and Styling 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!
