Adding different colors to the same plotting line

조회 수: 16 (최근 30일)
Hermes Chirino
Hermes Chirino 2018년 12월 4일
편집: Adam Danz 2023년 6월 25일
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')

채택된 답변

Adam Danz
Adam Danz 2018년 12월 4일
편집: Adam Danz 2023년 6월 25일
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
Hermes Chirino
Hermes Chirino 2018년 12월 4일
great, it worked, thanks Adam.
Adam Danz
Adam Danz 2018년 12월 4일
Great!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Labels and Styling에 대해 자세히 알아보기

태그

제품


릴리스

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by