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!

3 commentaires

Paulo Silva
Paulo Silva le 25 Fév 2011
Modifié(e) : Jan le 29 Jan 2018
fig=figure;
hax=axes;
x=0:0.1:10;
hold on
plot(x,sin(x))
SP=1; %your point goes here
line([SP SP],get(hax,'YLim'),'Color',[1 0 0])
Benita
Benita le 26 Fév 2023
(4x3+y3 )dx+(3xy²-8y3)dy=0

Connectez-vous pour commenter.

 Réponse acceptée

Michelle Hirsch
Michelle Hirsch le 28 Août 2023
Modifié(e) : MathWorks Support Team le 28 Avr 2022

74 votes

Woohoo - this is built into MATLAB now, as of R2018b! 
If you are running R2018b or later, you can use the “xline” and “yline” functions. For example, create a vertical line at x=5:
xline(5)
Create a horizontal line at y=10:
yline(10)
Starting in R2021a, you can create multiple horizontal or vertical lines in one pass. For example, create vertical lines at x=1, x=2, and x=3:
xline([1 2 3])
If you are running R2018a or earlier, use 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)])

10 commentaires

John D'Errico
John D'Errico le 2 Avr 2020
Modifié(e) : Adam Danz le 18 Jan 2023
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.
Update: the unrequested output issue was fixed in R2020a.
Jairo Domech
Jairo Domech le 8 Mai 2020
this code is nice thank you guys.
Peter Beringer
Peter Beringer le 25 Oct 2020
Can this also be used to create a vertical line on the Z axis?
Peter Beringer
Peter Beringer le 25 Oct 2020
There is a function call 'zline', but it doesn't do what I'd hoped.
Basically, I want to add a vertical line to a trisurf plot at x = 5.5 and y = 5.5, with the line extending up along the z axis to the maximum Z value (or some aribtrary 'max Z value', 60 will do).
Is such a thing even possible?
xline() and yline() have behavior built into them that they show up no matter how you pan or zoom (provided that the reference values are within range.)
As you do not appear to need that behavior, you can use
ZL = zlim();
line([x x], [y y], [ZL(1), 60])
Christopher Thomas
Christopher Thomas le 21 Fév 2021
hello....
I'm trying to use
>> vline(x) to insert onto a plot
but I get the message 'Unrecognized function or variable 'vline'.'
Does anyone know why this is? I'm using R2020b and following a video tutorial on R2019a....
Walter Roberson
Walter Roberson le 21 Fév 2021
Modifié(e) : Walter Roberson le 11 Déc 2024
in https://www.mathworks.com/matlabcentral/answers/2031-adding-vertical-line-to-plot#answer_207851 Michelle posted a link to a file exchange contribution that defines vline.
Roberto Chang
Roberto Chang le 23 Août 2021
Hello all! do you know if this magical (awesome) feature can be done in Z axis for bar3?
Charles
Charles le 10 Déc 2024
Thank you for clear answer. I find plotting in MATLAB a little confusing
@Roberto Chang There is no equivalent function (like zline) to xline and yline. But as of release R2024b there is a function that I think will satisfy your needs to create a way to identify a constant Z value: constantplane.
x = randn(1, 1e6);
y = randn(1, 1e6);
histogram2(x, y, Normalization = 'cdf')
constantplane('z', 0.5, DisplayName = "z = 0.5")
constantplane('x', 0, DisplayName = "x = 0", FaceColor = 'r')
constantplane('y', 0, DisplayName = "y = 0", FaceColor = 'c')
legend show
Maybe not the most visually appealing example I've written, but it should show the functionality.

Connectez-vous pour commenter.

Plus de réponses (11)

Muhammad
Muhammad le 8 Juil 2014

40 votes

line([x x], [y1 y2]); is the easy command;

4 commentaires

Ryuji Segawa
Ryuji Segawa le 29 Sep 2016
you are a genius!
Bin Miao
Bin Miao le 5 Déc 2017
Thanks!
Claire Flashman
Claire Flashman le 11 Fév 2018
Thank you!
Christian Sanchez
Christian Sanchez le 8 Mai 2020
Genial

Connectez-vous pour commenter.

carolina franco
carolina franco le 26 Oct 2017
Modifié(e) : MathWorks Support Team le 8 Nov 2018

17 votes

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:

4 commentaires

Junayed Chowdhury
Junayed Chowdhury le 30 Jan 2018
Modifié(e) : Stephen23 le 19 Mar 2018
This one works fantastically...Thanks a lot :D cheers!!
Camilo Malagon Nieto
Camilo Malagon Nieto le 19 Mar 2018
Modifié(e) : Camilo Malagon Nieto le 23 Avr 2018
This is AMAZING!!! because it makes the line automatically covering the data area of the plot. So I do not need to do extra work of finding where the line should start and should end. It works for several different plots that had diferent y-axis ranges.
Edward Manson
Edward Manson le 28 Août 2019
Modifié(e) : Edward Manson le 28 Août 2019
What an absolute god, thankyou
Rasmus Ringsborg Nielsen
Rasmus Ringsborg Nielsen le 11 Mar 2021
Thank you so much, works perfect!!

Connectez-vous pour commenter.

Mark
Mark le 12 Mar 2013
Modifié(e) : Mark le 12 Mar 2013

10 votes

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).
Steven Lord
Steven Lord le 1 Nov 2018

8 votes

If you're using release R2018b or later, use the xline or yline functions to create lines with constant x or y values respectively.
the cyclist
the cyclist le 25 Fév 2011

6 votes

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
James le 28 Mar 2014
Modifié(e) : James le 28 Mar 2014

3 votes

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

5 commentaires

Steven
Steven le 6 Avr 2015
Why is there no documentation on this function? It works great but it is difficult to motivate putting undocumented methods in code that I share with others.
Ben
Ben le 9 Sep 2016
@Steven That's because undocumented features can be removed at any time, as this feature was.
Adrian Peters
Adrian Peters le 8 Fév 2020
Déplacé(e) : DGM le 25 Fév 2023
Sorry, but what does (-2:5).^2-1 do? I dont know, how to calculate the ^2-1.
Walter Roberson
Walter Roberson le 8 Fév 2020
Déplacé(e) : DGM le 25 Fév 2023
-2:5 is the list of values -2 -1 0 1 2 3 4 5 . The .^2 squares each element of the list giving you 4 1 0 1 4 9 16 25 . Then you subtract 1 from each giving you 3 0 -1 0 3 8 15 24
Adrian Peters
Adrian Peters le 8 Fév 2020
Déplacé(e) : DGM le 25 Fév 2023
Now it makes sense to me! Thank you a lot!

Connectez-vous pour commenter.

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.

2 commentaires

Walter Roberson
Walter Roberson le 23 Avr 2018
If you use line() instead of plot() then you do not need the "hold". line() is one of the primitives that always adds to the current plot; it is the "high level plotting routines" that clear the current axes before plotting and need the "hold"
Thanks!

Connectez-vous pour commenter.

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.
Guy Cohen
Guy Cohen le 22 Nov 2022

1 vote

You can use arrayfun
x=1:180;
figure;plot(x,sind(x)); %-- your graph
vLines=[20 40 50 120];%-- vector of lines to plot
hold on; arrayfun(@xline,vLines);%-- plot vertical lines

3 commentaires

You could, but xline accepts a vector of values, so you can just
x=1:180;
plot(x,sind(x)); %-- your graph
xline([20 40 50 120])
Guy Cohen
Guy Cohen le 22 Nov 2022
Agree, but xline accepts a vector only in the latest versions
Walter Roberson
Walter Roberson le 11 Déc 2024
It looks like xline starts handling vectors in either R2020a or R2020b (not sure which at the moment.)

Connectez-vous pour commenter.

amit
amit le 27 Fév 2025

0 votes

%% generation of tanwave
clear all
close all
x=0:0.001:20;
a=2;
y=a*cos(x);
plot(x,y);
xlabel ("time axis")
ylabel("amplitude")
title("tanwave")
grid on

1 commentaire

Walter Roberson
Walter Roberson le 27 Fév 2025
This does not generate tan wave -- it generates cosine wave.
It is not clear how this code is intended to satisfy the question of how to generate reference lines?

Connectez-vous pour commenter.

Catégories

En savoir plus sur Graphics Object Properties dans Centre d'aide et File Exchange

Tags

Aucun tag saisi pour le moment.

Community Treasure Hunt

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

Start Hunting!

Translated by