MATLAB: How to put gridlines on the bottom layer and axes on the top layer

axesgridlineslayers

I would like to wedge data between gridlines and axes. Using ax.Layer = 'top', gridlines are plotted over the data along with the axes (figure 1). But using ax.Layer = 'bottom' results in data over the axes (figure 2). See the two examples below.

Best Answer

Perhaps overplotting the left and right axes (and the tick lines if you want the tick lines) will do what you want:
x = linspace(0, 1, 1000); % Create Data

y = rand(1, 1000); % Create Data
figure
plot(x, y)
ax = gca;
ax.Layer = 'bottom';
tl = ax.TickLength(1);
yaxtl = diff(xlim)*tl;
yt = ax.YTick;
hold on
plot([1 1]*min(xlim), ylim, '-k') % Left Vertical Axis

plot([1 1]*max(xlim), ylim, '-k') % Left Vertical Axis
plot([0; yaxtl]*ones(size(yt)), [yt; yt], '-k') % Left Y-Ticks
plot([max(xlim); max(xlim)-yaxtl]*ones(size(yt)), [yt; yt], '-k') % Right Y-Ticks
hold off
grid
This overplots the vertical axes and the tick lines, so neither will be hidden. If you don’t want the tick lines, don’t plot them.