Reputation: 4477
I want to add a x-axis line at 0 to a Matlab figure so that I can compare my data to see if it is positive or negative when saving the figures to a jpg. What is the best way to do this? I know you can use line()
but it just seems cumbersome because you need to specify the x and the y ranges. Is there an easier way?
Upvotes: 16
Views: 59243
Reputation: 60645
Since MATLAB R2018b there is yline
for this purpose:
yline(0)
draws a horizontal line at y==0
.
Upvotes: 1
Reputation: 53
plot()
command or stem()
. A figure window will open.Upvotes: 1
Reputation: 7043
A vline
and hline
command like in GNU R would be great, but I could not find a shorter solution than
plot(1:10,sin(1:10));
line(xlim,[0 0],'Color','r')
Upvotes: 6
Reputation: 124563
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');
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.
Upvotes: 32
Reputation: 4221
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')
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.
Upvotes: 7
Reputation: 22588
I don't believe there is a built-in way that is more convenient. I use hline()
and vline()
from FileExchange, which work like a charm:
http://www.mathworks.com/matlabcentral/fileexchange/1039
Upvotes: 6