In MATLAB, is there a way to set the GRID at a spacing different from the ticks on the axes?

2,525 views (last 30 days)
In MATLAB, is there a way to set the GRID at a spacing different from the ticks on the axes?

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 27 Jun 2009
Currently the ticks and grid line spacing are associated and so the only way to change grid spacing is to change the tick spacing. Here are some examples:
figure
plot(1:100)
set(gca,'xtick',[0:13:100])
set(gca,'ytick',linspace(0,100,13))
% The following code changes the minor grid
% spacing by adjusting the tick spacing:
figure
plot(1:100);
grid on
grid minor
set(gca,'xtick',[0:50:100])
set(gca,'ytick',[0:50:100])

More Answers (2)

Udo Ruprecht
Udo Ruprecht on 6 Feb 2015
I have another idea
x=[20:0.1:80];
y=sin(x);
plot(x,y,'r','Linewidth',2)
ylim([0 4]);
xlim([0 100]);
% gridlines ---------------------------
hold on
g_y=[0:0.1:4]; % user defined grid Y [start:spaces:end]
g_x=[0:2:100]; % user defined grid X [start:spaces:end]
for i=1:length(g_x)
plot([g_x(i) g_x(i)],[g_y(1) g_y(end)],'k:') %y grid lines
hold on
end
for i=1:length(g_y)
plot([g_x(1) g_x(end)],[g_y(i) g_y(i)],'k:') %x grid lines
hold on
end
print(1,'-dpng','-r300','K1') %save plot as png (looks better)
  2 Comments
Amin Rajabi
Amin Rajabi on 12 Jan 2018
Thanks for your answer, it solved my problem. However, I think a bit of modification makes the code better. In the code instead of using
for i=1:length(g_x)
It's better to use for i=2:length(g_x)-1 (The same for another for loop.)
You can compare the resulted pics for both cases. For the first code, it plots some small grids (ticks) out of the box.

Sign in to comment.


Dillen.A
Dillen.A on 14 Aug 2018
Edited: Dillen.A on 14 Aug 2018
In my opinion the most elegant solution: make a 2nd axes with the desired grid lines. In this axes you hide the tickmarks, ticklabels and use linkaxes to the original axes handle. An example:
figure;
%%example plot from the double axes matlab help
x = 0:0.1:40;
y = 4.*cos(x)./(x+2);
plot(x,y,'r','Linewidth',1)
ylim([-1 2]);
xlim([0 40]);
%%create a second axes.
ax1 = gca; % the first axes
ax2 = axes('Position',ax1.Position,...
'XAxisLocation','bottom',...
'YAxisLocation','left',...
'Color','none',...
'Ylim',ax1.YLim,...
'XLim',ax1.XLim,...
'TickLength',[0 0],...
'YTick', [ax1.YLim(1):3/5:ax1.YLim(2)], ...
'XTick', [ax1.XLim(1):7.5:ax1.XLim(2)], ...
'YTickLabel', [], ...
'XTickLabel', [] );
linkaxes([ax1 ax2],'xy')
grid on
set(gcf,'CurrentAxes',ax1); % return to ax1
I'm sure you can remove the AxisLocation properties, as they shouldn't matter. You can also set ax2 color/opacity.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!