MATLAB: How to make grid lines appear on top of the image but below the text objects in MATLAB 7.5 (R2007b)

dwhhgMATLAB

When I open an image in a figure window and add text the grid lines appear on top of the text.
For example:
r=ones(100);
imagesc(r)
txt1 = ['this is a test'];
tx1 = text(50,50,txt1,'units','data','backgroundcolor',[1 0 0])
grid on
If I set the LAYER property of the axes to BOTTOM then the gridlines are behind both the image and the text.

Best Answer

In general, if you want to control what objects appear in front of gridlines you can create them in a separate axes on top of that one which includes that grid. You can then turn off the tick marks and tick labels of the second axes and set the COLOR to NONE. Finally, you can use the LINKAXES command to ensure that both axes scroll and zoom together. Below is some sample code.
fig1 = figure(1);
ax1 = axes;
r=ones(100);
imagesc(r)
grid on
ax2 = axes('XTick', [], 'YTick', [],'Color','none');
linkaxes([ax1 ax2]);
txt1 = ['this is a test'];
tx1 = text(50,50,txt1,'units','data','backgroundcolor',[1 0 0])
If the UNITS property is set to NORMALIZED then the text will not zoom or scroll correctly.