Adding different colors to the same plotting line
16 views (last 30 days)
Show older comments
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 Comments
Accepted Answer
Adam Danz
on 4 Dec 2018
Edited: Adam Danz
on 25 Jun 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')
More Answers (0)
See Also
Categories
Find more on Labels and Styling in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!