How to draw line vertical to Y-axis?
22 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
M G
am 2 Nov. 2011
Kommentiert: Walter Roberson
am 12 Apr. 2021
Hey Matlab users,
If a = [1 2 3 4 5 6 7]; and b = [1 4 7 10 7 4 1]; and the plot it by : figure,plot(a,b), how can I draw let's say a red line vertical to the value 4 and 7 in the y-axis (parallel to x-axis)? So that i can see the window between 4 and 7.
Thanks so much in advance,
Mehdi
0 Kommentare
Akzeptierte Antwort
Walter Roberson
am 2 Nov. 2011
yL = get(gca,'YLim');
line([3 3],yL,'Color','r');
line([5 5],yL,'Color','r');
and if you are wanting to draw vertical lines at 4 and 7, you would just change the code to
yL = get(gca,'YLim');
line([4 4],yL,'Color','r');
line([7 7],yL,'Color','r');
Perhaps what you want is instead horizontal lines? If so then
xL = get(gca,'XLim');
line(xL,[4 4],'Color','r');
line(xL,[7 7],'Color','r');
7 Kommentare
Gourav Mitra
am 12 Apr. 2021
it works fine but in some case, the vertical line doesnot fit or cover the entire ylimit.
Walter Roberson
am 12 Apr. 2021
These days, see yline()
If you get the current ylim and use it to draw, and then you zoom or pan, then the code I posted back then will not adjust to draw according to the new limits. However, the newer yline() should do that.
Weitere Antworten (5)
Noushin Farnoud
am 15 Nov. 2011
If you want to draw a line that spans the entire xlim or ylim of your figure, then I suggest that you use hline or vline functions from: http://www.mathworks.com/matlabcentral/fileexchange/1039-hline-and-vline
You can also plot multiple vertical or horizontal lines at the same time using these functions. For example: hline([5,6,8]) draws 3 horizontal lines at x=5, x=6 and x=8.
0 Kommentare
James
am 28 Mär. 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');
0 Kommentare
Wayne King
am 2 Nov. 2011
a = [1 2 3 4 5 6 7];
b = [1 4 7 10 7 4 1];
plot(a,b)
hold on
plot(a,4*ones(length(b)),'r');
plot(a,7*ones(length(b)),'r');
1 Kommentar
Walter Roberson
am 2 Nov. 2011
A bit murky if "a" does not happen to be in sorted order, especially if the drawingmode is set to xor
Siehe auch
Kategorien
Mehr zu Graphics Performance finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!