How to plot vertical lines?

198 views (last 30 days)
andrea
andrea on 20 Oct 2014
Commented: Alberto Sivera on 17 Nov 2021
This is the script:
x=[0:0.1:10]; x1=5;
plot(x,2*sin(x),x,5*sin(x),x,cos(x));
line([x1 x1],???????);
I would like to plot the vertical line from the top to the bottom without knowing the y-axis limits.
Thanks in advance!

Accepted Answer

Azzi Abdelmalek
Azzi Abdelmalek on 20 Oct 2014
x=[0:0.1:10];
x1=5;
plot(x,2*sin(x),x,5*sin(x),x,cos(x));
y1=get(gca,'ylim')
hold on
plot([x1 x1],y1)
  2 Comments
Brando Miranda
Brando Miranda on 14 Oct 2017
can u explain?
Eric Sargent
Eric Sargent on 23 Jun 2020
Starting in R2018b you can use xline and yline.

Sign in to comment.

More Answers (5)

Kelly Kearney
Kelly Kearney on 20 Oct 2014
line([x1 x1], get(gca, 'ylim'));
Or this function will automate the process, if you have a lot of reference lines to plot.
  5 Comments
Image Analyst
Image Analyst on 17 Nov 2021
@Alberto Sivera if you have R2018b or later, you should really be using xline() like @Pierre Tallotte shows in his answer below.
xline(x1, 'Color', 'r', 'LineWidth', 2);
Alberto Sivera
Alberto Sivera on 17 Nov 2021
thank you, but unfortunately I have the r2017b version and i'm too lazy to update it :)

Sign in to comment.


Pierre Tallotte
Pierre Tallotte on 10 Apr 2020
The xline function is just what you need:
x=[0:0.1:10]; x1=5;
plot(x,2*sin(x),x,5*sin(x),x,cos(x));
xline(x1);

Image Analyst
Image Analyst on 20 Oct 2014
simply pass in ylim for the y array:
line([x1 x1], ylim);
  3 Comments
Image Analyst
Image Analyst on 27 Jul 2017
Not sure.
ylim() is not returning the correct y axis range limits.
That certainly is weird. I'd call tech support on this one.
Jan
Jan on 28 Aug 2017
@Liyuan: See my answer.

Sign in to comment.


Jan
Jan on 28 Aug 2017
If the axes is scaled, e.g. when adding new objects or for printing, using the current limits for the Y-position is fragile. You can use much larger positions and exclude the line from the list of objects, which influence the auto-scaling:
YL = get(gca, 'ylim');
YR = YL(2) - YL(1);
YL = [YL(1) - 1000 * YR, YL(2) + 1000 * YR];
line([5, 5], YL, 'YLimInclude', 'off')
'YLimInclude' in undocumented and might be removed in the future.

Jefferson Martinez Saavedra
Does someone know how to get/download xline and yline functions? I have R2018a's version of MATLAB.
Thank you in advance.
  1 Comment
Image Analyst
Image Analyst on 23 Oct 2020
If you dont' have xline and yline you can use line():
xl = xlim;
yl = ylim;
line([x, x], yl); % Old way of doing xline().
line(xl, [y, y]); % Old way of doing yline().

Sign in to comment.

Categories

Find more on Interactive Control and Callbacks 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!