matlabmatlab-figuregridlines

Too many grid lines in log plot


When I add grid lines to a log plot, it seems to automatically add every possible grid line, and I would like to only include the major lines. I tried turning the minor ticks off, but it has no effect.

For example:

loglog([0.000001,0.1],[0.000001,0.1])
grid on
gca.YAxis.MinorTick = 'off'

enter image description here

How can I just have grid lines at the labelled axes ticks?


Solution

  • The loglog plot has unusual axes, because the minor tickmarks are enabled by default as you'd normally expect from the major tickmarks. So this behaviour from the grid documentation is a bit of a grey area:

    grid on displays the major grid lines for the current axes returned by the gca command. Major grid lines extend from each tick mark.

    Note that most of the plots in the documentation for loglog use grid on and show the minor(ish) grids as you're seeing, so I doubt this is unexpected behaviour from MathWorks' perspective.

    Since there's no way to call grid whilst explicitly disabling the minor grid lines, (as it should be the default behaviour), you'll have to manage the grids more granularly with set after creating the axes. You can enable the major grids and disable the minor grids in one command without using grid() at all...

    Tested in R2020b Update 5:

    loglog([0.000001,0.1],[0.000001,0.1])
    set(gca,'xminorgrid','off','yminorgrid','off','xgrid','on','ygrid','on')
    

    plot without minor gridlines


    Edit: From conversation in the comments, Luis suggested that grid on, grid minor should work. However, testing in R2020b it does not. Calling these commands in two separate calls does work the same way as using set above:

    loglog([0.000001,0.1],[0.000001,0.1])
    grid on
    grid minor
    

    I assume because the graphics buffer has to be flushed before grid minor works to remove gridlines, maybe because if not there's nothing there to remove. You could disguise this as a single line using drawnow to flush the buffer, but at that point I think I'd recommend just using set shown above

    loglog([0.000001,0.1],[0.000001,0.1])
    grid on; drawnow(); grid minor
    

    Speculating, maybe the author of loglog decided the minor grids with their variable spacing made the plot look more "logish"? i.e. it's more obviously a nonlinear scale.