How do I draw a vertical refline in matlab? e.g. I want to plot a line of x=5. Obviously using inf does not help at all. Can anyone give some advice?
Asked
Active
Viewed 2.9k times
3
-
See https://stackoverflow.com/q/8086943/7328782 for a similar question regarding horizontal lines. – Cris Luengo Mar 26 '19 at 12:54
-
Easy way using `stem` in this [answer](https://stackoverflow.com/a/55355699/8239061) for those with releases prior to `xline` 's release in R2018b. – SecretAgentMan Mar 26 '19 at 13:16
-
Possible duplicate of [How to draw horizontal and vertical lines in MATLAB?](https://stackoverflow.com/questions/28334660/how-to-draw-horizontal-and-vertical-lines-in-matlab) – SecretAgentMan Dec 17 '19 at 22:33
5 Answers
10
You can create a vector with many identical values for x. Something like this:
x = 5*ones(1,100);
y = 1:100;
plot(x,y)
or use the line function:
line([5,5],[0,10])
To automatically detect the range of line, use ylim:
plot(1:10)
line([5,5],ylim)

Molly
- 13,240
- 4
- 44
- 45
-
I want it to automatically determine the endpoints of the line instead of me specifying the two points... – OneZero Jul 22 '13 at 21:57
-
Note! `ylim` is a matlab function in and of itself that does exactly what you have called it to do - there is no need to override the builtin using the line `ylim = get(gca,'ylim')` – Hugh Nolan Jul 22 '13 at 22:12
-
-
1You can also use `plot` itself `plot([5 5], ylim)`. That makes it easier to combine it with other plot commands. – Mohsen Nosratinia Jul 22 '13 at 22:44
1
There is an excellent answer over on https://stackoverflow.com/a/8108766/1194420 repeated below for convenience. (Please go there an up vote the original answer) ---
There exist an undocumented function graph2d.constantline:
plot(-2:5, (-2:5).^2-1)
%# vertical line
hx = graph2d.constantline(0, 'LineStyle',':', 'Color',[.7 .7 .7]);
changedependvar(hx,'x');
%# horizontal line
hy = graph2d.constantline(0, 'Color',[.7 .7 .7]);
changedependvar(hy,'y');

Community
- 1
- 1

James McCorrie
- 2,283
- 3
- 18
- 22
1
The function refline
lets you specify gradient and intercept.

Cris Luengo
- 55,762
- 10
- 62
- 120

user3484718
- 11
- 1
1
You can use refline and then edit the XData and YData properties to create a vertical line.

Jakob Heiden
- 11
- 2