另一种方法是使用内置的网格:
h=gca;
grid on % turn on major grid lines
grid minor % turn on minor grid lines
% Set limits and grid spacing separately for the two directions:
h.XAxis.Limits=[-1,1];
h.XAxis.TickValues=-1:0.5:1;
h.XAxis.MinorTickValues=-1:0.2:1;
h.YAxis.Limits=[-1,1];
h.YAxis.TickValues=-1:0.5:1;
h.YAxis.MinorTickValues=-1:0.2:1;
% Must set major grid line properties for both directions simultaneously:
h.GridLineStyle='-'; % the default is some dotted pattern, I prefer solid
h.GridAlpha=1; % the default is partially transparent
h.GridColor=[0,0,0]; % here's the color for the major grid lines
% Idem for minor grid line properties:
h.MinorGridLineStyle='-';
h.MinorGridAlpha=1;
h.MinorGridColor=[1,0,0]; % here's the color for the minor grid lines
注意,您可以缩短以上代码通过一次设置多个属性:
h=gca;
grid on
grid minor
set(h.XAxis,'Limits',[-1,1],'TickValues',-1:0.5:1,'MinorTickValues',-1:0.2:1)
set(h.YAxis,'Limits',[-1,1],'TickValues',-1:0.5:1,'MinorTickValues',-1:0.2:1)
set(h,'GridLineStyle','-','GridAlpha',1,'GridColor',[0,0,0])
set(h,'MinorGridLineStyle','-','MinorGridAlpha',1,'MinorGridColor',[1,0,0])