# Add various horizontal lines to a plot

3,948 views (last 30 days)
FC93 on 7 Oct 2016
Commented: Steven Lord on 11 Feb 2021
How can I add various horizontal lines to a plot?
I have a plot and now I want to add several horizontal lines. I would like to draw a horizontal line between x=-6 to x=-2 and another horizontal line between ×=3 and x=10.
Could someone show me a way to do it? Thank you.

Marc Jakobi on 7 Oct 2016
Edited: MathWorks Support Team on 28 Nov 2018
If you want the line to have specific end points, you can use the line function. For example, this code draws a horizontal line at y = 5 between the points x = -6 and x = -2.
y = 5;
line([-6,-2],[y,y])
Starting in R2018b, you can use the xline and yline functions to draw vertical and horizontal lines, respectively. For example, this code draws a horizontal line at y = 5. The horizontal line extends in both the positive and negative directions with no end points.
yline(5)
Steven Lord on 11 Feb 2021
plot(1:10)
h = yline(5, 'r--', 'LineWidth', 4); You can change various properties of the line using its handle, or you can set those properties when the line is constructed like I did with the linespec ('r--') and the property names (LineWidth).

Massimo Zanetti on 7 Oct 2016
Horizontal line at what y coordinate? Fix y and then plot the line, for example if y=5:
x=1:12;
y=5;
plot(x,y*ones(size(x)))
##### 2 CommentsShowHide 1 older comment
Rolando Murilli on 16 Aug 2020
Thanks!!

KSSV on 7 Oct 2016
x=linspace(-6,-2,M) ;
%%y range
N = 50 ;
y = linspace(-5,5,N) ; % you have to select y range
for i = 1:N
xi = x ;
yi = y(i)*ones(size(xi)) ;
plot(xi,yi,'r')
hold on
end
x=linspace(3,10,M) ;
%%y range
N = 50 ;
y = linspace(-5,5,N) ;
for i = 1:N
xi = x ;
yi = y(i)*ones(size(xi)) ;
plot(xi,yi,'r')
hold on
end
xlim([-10 40])
FC93 on 7 Oct 2016