MATLAB: How to show the major grid lines as dotted and the minor grid lines as solid in MATLAB 7.8 (R2009a)

MATLAB

I am trying to set the major grid lines to have a dashed linestyle, and the minor gridlines to have a solid linestyle:
figure;
plot(1:10)
grid on
set(gca, 'xminorgrid', 'on')
set(gca,'MinorGridLineStyle','-')
set(gca,'GridLineStyle','--')
However, the resulting major grid lines for the x-axis are solid and not dotted as I intended.

Best Answer

  • This issue has to do with the fact that major grid lines overlap with the minor grid lines at the points with the major ticks. When you specify the 'MinorGridLIneStyle' as solid '-', and the 'GridLineStyle' as dashed '--', the dashed major grid lines are plotted on top of the solid minor grid lines and thus cannot be seen.
    The ability to change this behavior of the grid lines is currently not available in MATLAB. To work around this issue, you can manually draw the solid minor grid lines using the PLOT command as outlined in the example below:
    % generate a plot with the dashed major grid lines
    figure
    plot(1:10)
    grid on
    set(gca,'GridLineStyle','--')
    axis([0 10 0 10])
    % specify the minor grid vector
    xg = 0:0.25:10;
    % specify the Y-position and the height of minor grids
    yg = [0 10];
    xx=repmat(xg,[2 1]);
    yy=repmat(yg',size(xg)');
    % get rid of the elements in the xx vector corresponding to the major grid
    % lines
    xx(:,1:4:length(xg))=[];
    yy(:,1:4:length(xg))=[];
    % plot the minor grid lines
    hold on
    h_minorgrid = plot(xx,yy,'k');