Put Axes in the Center

advertisement
Put Axes in the Center
Matlab has a strong graphing capability. But there is one thing which often makes me,
maybe others, uneasy. When you draw a plot, the x-axis is always on the left or right,
y-axis is always on the top or bottom, if you want to put the axes in the center of the plot
window, as far as I know, there are no simple Matlab commands can make it. The
following program is written for this purpose. Maybe still someone is not satisfied with
the output, well, this is the first step to perfect.
The usage is very simple. Copy the following codes into your Matlab script window, give
it a name, say, ace.m, then run it, following the prompt, feed x, y, the intersection of two
axes or the origin, the number of x-ticks and y-ticks, after seconds, done!
x=input('Please Input the X-values: ');
y=input('Please Input the Y-values: ');
cx=input('Please Input the Center of X-axis: ');
cy=input('Please Input the Center of Y-axis: ');
nx=input('Please Input the Number of X-ticks: ');
ny=input('Please Input the Number of Y-ticks: ');
hx=max(abs(max(x)-cx), abs(min(x)-cx));
hy=max(abs(max(y)-cy), abs(min(y)-cy));
x0=cx-hx; x1=cx+hx; y0=cy-hy; y1=cy+hy;
plot(x,y,'LineWidth',2);
axis off; hold on;
xaxis=cy*ones(size((x0-2*hx/nx):(2*hx/nx):(x1+2*hx/nx)));
plot((x0-2*hx/nx):(2*hx/nx):(x1+2*hx/nx),xaxis,'r');
hold on;
yaxis=cx*ones(size((y0-2*hy/ny):(2*hy/ny):(y1+2*hy/ny)));
plot(yaxis,(y0-2*hy/ny):(2*hy/ny):(y1+2*hy/ny),'r');
hold on;
xtw=hy/ny/6; ytw=hx/nx/6;
for xx=x0:(2*hx/nx):x1;
t1=xx*ones(2,1); t2=[cy-xtw,cy+xtw];
plot(t1,t2,'-r');
if(xx~=0)
text(xx,cy-3.5*xtw,num2str(round(xx*10)/10),'HorizontalAlignment','center');
end;
hold on;
end;
for yy=y0:(2*hy/ny):y1;
t1=yy*ones(2,1); t2=[cx-ytw,cx+ytw];
plot(t2,t1,'-r');
if(yy~=0)
text(cx-1.5*ytw,yy,num2str(round(yy*10)/10),'HorizontalAlignment','right');
end;
hold on;
end;
plot(x,y);
text(cx-1.5*ytw,cy-3.5*xtw,'0','HorizontalAlignment','right');
axis on;
set(gca,'xtick',[],'ytick',[]);
hold off;
Example: Plot y = e
−0.02 x
sin(0.5 x) , where x=[0,200], the origin is (0,0), the number of x-ticks is
20 and the number of y-ticks is 10.
Solution: First generate x, and y. In the command window, write
x=0:0.01:200; y=exp(-0.02*x).*sin(0.5*x);
Then run the program. Input x, y, 0, 0, 20 (the number of x-ticks) and 10 (the number of y-ticks)
sequentially. Here is the desired plot. Cool?
Download