5.456 views (last 30 days)

Hi there,

Can anyone please tell me how I can add a vertical line to my plot at a specified sample point? For example, I have a a 1x41 vector of intensity values, and I would like to add a vertical line on the center sample (sample number 21).

Many thanks!

Michelle Hirsch
on 29 Jan 2016

Edited: Michelle Hirsch
on 2 Apr 2020

Woohoo - this is built into MATLAB now, as of R2018b! You can use xline and yline to create lines with constant x or y values respectively.

Basic usage couldn't be much easier:

If you are on older releases, another option is hline and vline from the File Exchange: http://www.mathworks.com/matlabcentral/fileexchange/1039-hline-and-vline

John D'Errico
on 2 Apr 2020

There is one thing that frustrates me about yline and xline (I do love them, don't get me wrong.)

A standard MATLAB paradigm has always been that if you don't have a return argument, then none is returned, at least from functions that return handles. For example,

>> plot(rand(5),'.')

>>

Returns nothing. However, if I wish to get the handle, then I can. Just specify a return argument. Essentially, plot checks nargout before it exits.

H = plot(1:5)

H =

Line with properties:

Color: [0 0 1]

LineStyle: '-'

LineWidth: 0.5

Marker: 'none'

MarkerSize: 6

MarkerFaceColor: 'none'

XData: [1 2 3 4 5]

YData: [1 2 3 4 5]

ZData: [1×0 double]

Show all properties

This is compeltely standard behavior in MATLAB. ANY function that returns a graphics handle has always operated that way.

HOWEVER, xline and yline fail to follow that standard paradigm. They ALWAYS return a handle to the line as created.

xline(2)

ans =

ConstantLine with properties:

InterceptAxis: 'x'

Value: 2

Color: [0.15 0.15 0.15]

LineStyle: '-'

LineWidth: 0.5

Label: ''

DisplayName: ''

Show all properties

Some of the time it is useful to get the handle. But if I want it, then I can always grab it as an output argument. Would it have been that difficult to check to see if an output argument was requested? All the authors of xline and yline needed to do was one simple check at the end of the code:

if nargout == 0

clear YL % or whatever is the internal name of the handle variable

end

My point is, MATLAB functions should ALWAYS be consistent in how they work.

I should never need to remember to add a semi-colon after calls to functions like xline and yline to kill the spurious and unwanted graphics handle being dumped to the command window. Essentially, I consider this a bug in the code of those two functions.

carolina franco
on 26 Oct 2017

Edited: MathWorks Support Team
on 8 Nov 2018

You can plot a horizontal or vertical line using the “plot” function with this pattern:

- Horizontal line:

plot([x1 x2],[y y])

- Vertical line:

plot([x x],[y1 y2])

For example, plot a vertical line at x = 21. Set the y values using the y-axis limits of the axes.

y = ylim; % current y-axis limits

plot([21 21],[y(1) y(2)])

As Steven suggested, starting in R2018b, you can use the “xline” and “yline” functions instead. For more information, see:

Camilo Malagon Nieto
on 19 Mar 2018

Mark
on 12 Mar 2013

Edited: Mark
on 12 Mar 2013

Probably the simplest way:

Choose the x-value where you want the line "xval." Choose the minimum y value to be displayed on your graph "ymin" and the maximum y value to be displayed on your graph "ymax."

x=[xval,xval];

y=[ymin,ymax];

plot(x,y)

Flaws with this method: probably will look silly if you use '-x' or '-.', these mark your specific points on the line, but you'll only have two (at least they're endpoints).

the cyclist
on 25 Feb 2011

One way:

figure

x = rand(1,41);

y = 1:41;

plot(x,y,'r.');

line([x(21) x(21)],[0 41]);

set(gca,'YLim',[0 41])

James
on 28 Mar 2014

Edited: James
on 28 Mar 2014

There is an excellent answer over on http://stackoverflow.com/a/8108766/1194420 repeated below for convenience. ---

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');

Steven
on 6 Apr 2015

Ben
on 9 Sep 2016

@Steven That's because undocumented features can be removed at any time, as this feature was.

Pedro Luis Camuñas García-Miguel
on 13 Apr 2018

Maybe it is a bit late but I want to contribute, there is a really easy way to add vertical and horizontal lines, you just have to use a hold and then overlap them over the main plot.

Before declaring the original plot, add a hold on to ensure it will retain both plots, then plot the lines, with this structure:

hold on;

plot(the main function)

plot([x x],[0 y_max]) % Vertical Line

plot([o x_max],[y y]) % Horizontal line

Being:

x: location on horizontal axis where you place the vertical line.

y: location on vertical axis where you place the horizontal line.

x_max: point where you want the vertical line to end.

y_max: point where you want the horizontal line to end.

I hope this was useful to whoever consults this page.

Walter Roberson
on 23 Apr 2018

Julian Williams
on 9 Feb 2019

Small additional suggestion, say you want to label your line in the legend so that it has some meaning, or take advantage of some of the easy to use options in plot, then using "hold", the ylim from the current axis and the "repmat" is very useful. You can also make multiple vertical lines with some spacing using this technique.

figure

% make some sort of illustration

T = 1000;

A = 0.7;

h = [];

Y = cumsum(sqrt(0.05).*randn(T,1));

X = (1:T)./T;

I = find(X>A);

Y(I) = Y(I(1));

h(1) = plot(X,Y,'-k','linewidth',2);

hold on

dims = get(gca,'ylim');

yy = linspace(dims(1),dims(2),100);

xx = repmat(A,1,100);

h(2) = plot(xx,yy,':r','linewidth',2);

dims = get(gca,'xlim');

xx = linspace(dims(1),dims(2).*A,100);

yy = repmat(Y(I(1)),1,100);

h(3) = plot(xx,yy,':b','linewidth',2);

grid on

G = legend(h,'Particle Motion','Stopping Point','Stopped Value');

set(G,'location','best','interpreter','latex');

Just a thought.

Adrian Peters
on 8 Feb 2020

Sorry, but what does (-2:5).^2-1 do? I dont know, how to calculate the ^2-1.

Walter Roberson
on 8 Feb 2020

Opportunities for recent engineering grads.

Apply Today
## 1 Comment

## Direct link to this comment

https://nl.mathworks.com/matlabcentral/answers/2031-adding-vertical-line-to-plot#comment_3975

⋮## Direct link to this comment

https://nl.mathworks.com/matlabcentral/answers/2031-adding-vertical-line-to-plot#comment_3975

Sign in to comment.