MATLAB Answers

Add various horizontal lines to a plot

6.980 views (last 30 days)
FC93
FC93 on 7 Oct 2016
Answered: Muhamed Eliyas on 28 Nov 2020 at 15:28
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.

  0 Comments

Sign in to comment.

Accepted Answer

Marc Jakobi
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)
For more information on the yline function, see: https://www.mathworks.com/help/matlab/ref/yline.html

  3 Comments

FC93
FC93 on 7 Oct 2016
Exactly, thank you. Now I included all the horizontal lines I needed.
Stephen
Stephen on 23 Jan 2019
This helped me, too.
Is is also possible to draw a horizontal line of specified length BELOW a figure? I have a heatmap that plots certain data versus time on the x axis. I'd like to add a calibration bar just below the x axis.

Sign in to comment.

More Answers (3)

Massimo Zanetti
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)))

KSSV
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])

  1 Comment

FC93
FC93 on 7 Oct 2016
Thank you for your help.

Sign in to comment.


Muhamed Eliyas
Muhamed Eliyas on 28 Nov 2020 at 15:28
You go to the university every day from your home by Bus.Assume the velocity(v) of the bus in ten different location from your starting point to the university.Find the average velocity and acceleration(a) of the Bus. If the mass(m) of the bus with all the people inside is 11,000 kg find the force(F) of the bus in different locations.Plot the velocity, acceleration and force of the bus in one figure.Try to curve fitting the force of the bus using linear equation with minimization of the sum of squares of errors. "Can u help me out? "

  0 Comments

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!

Translated by