How to add a x-axis line to a figure? (matlab)

You could get this x range directly after the figure has been created. It goes a little something like this:

x=-2:5;
y=x.^2-1;

figure()
plot(x,y);

xlim = get(gca,'xlim');  %Get x range 
hold on
plot([xlim(1) xlim(2)],[0 0],'k')

enter image description here

Note that if you do any manual zooming out in the figure, the line might have to be redrawn to go over the entire new x range.


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

screenshot

The nice thing is that it internally implements a listener for the axes limits (handles change like pan, zoom, etc..). So the lines would appear to extend to infinity.