Adding a horizontal line to a plot

18 ビュー (過去 30 日間)
Simone
Simone 2014 年 12 月 6 日
コメント済み: Star Strider 2014 年 12 月 6 日
How do you use the line function to add a horizontal line to a plot?
For example,
To add a horizontal line to easily point out the maximum value.
I am trying to use it in a nested for loop. This is my code so far:
y =[99;1;0];
beta = [0.005, 0.05, 0.1];
nu = [0.05, 0.075, 0.1];
options=odeset();
for i = 1:length(beta)
for index = 1:length(nu)
[T,Y] = ode45(@sir_ode,[0 30], y,options,beta(i),nu(index));
figure
plot(T,Y)
xlabel('Time(days)')
ylabel('Population(%)')
legend('susceptible','infected','recovered')
title_name =sprintf('Beta = %.3f Nu = %.3f', beta(i), nu(index));
title(title_name)
% finds max infected values
infected_values = Y(:,2);
max_infected(i,index) = max(infected_values);
% find max time
index_number(i,index)=find(infected_values ==max(infected_values));
max_T(i,index) = T(index_number(i,index));
line([max_T(i),max_T(i)], ...
[0,max_infected(i)],'Color', [0 1 0])
end
end
Thank you.

採用された回答

Star Strider
Star Strider 2014 年 12 月 6 日
I couldn’t run your code. You can do something like this to plot a horizontal line at the maximum:
x = linspace(0,pi);
y = sin(x);
ymax = max(y);
figure(1)
plot(x, y, '-b')
hold on
plot(xlim, [1 1]*ymax, '-r')
hold off
axis([xlim 0 1.1])
  2 件のコメント
Simone
Simone 2014 年 12 月 6 日
Thank you for your help!
Star Strider
Star Strider 2014 年 12 月 6 日
My pleasure!

サインインしてコメントする。

その他の回答 (1 件)

Image Analyst
Image Analyst 2014 年 12 月 6 日
Your line is a vertical line because both the x values are the same. To get a horizontal line, from the x=0 (y) axis to the peak, you could do
[maxY, indexAtMaxY] = max(infected_values);
x1 = 0;
x2 = T(indexAtMaxY);
line([x1, x2], [maxY, maxY], 'Color', 'g', 'LineWidth', 2);
  1 件のコメント
Image Analyst
Image Analyst 2014 年 12 月 6 日
Needless to say, all that code about "index_number" is unnecessary so get rid of it.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeAnnotations についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by