MATLAB Answers

How can I change the gridline color without changing the tick and tick label colors in MATLAB?

855 views (last 30 days)
When I execute the following lines of code:
h= plot(rand(1, 100));
grid on
set(gca, 'XColor', 'r')
the color of the X-axis gridlines, X tick-marks and X tick-labels all become red.
I would like to selectively change the color of the gridlines alone, without changing the color of the X tick-marks and X tick-labels.

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 22 Jul 2020
Edited: MathWorks Support Team on 22 Jul 2020
The gridline color cannot be changed without affecting the tick-mark and tick-label colors in MATLAB prior to R2014b .
*In MATLAB R2014a and prior *you can work around this issue by plotting lines of the desired color on top of your figure using PLOT. The following example demostrates this approach:
h= plot(rand(1, 100));
hold on
grid on
% Obtain the tick mark locations
xtick = get(gca,'XTick');
% Obtain the limits of the y axis
ylim = get(gca,'Ylim');
% Create line data
X = repmat(xtick,2,1);
Y = repmat(ylim',1,size(xtick,2));
% Plot line data
plot(X,Y,'r')
After executing the above code, the color of the X-axis gridlines remain red, whereas the X tick-marks and X tick-labels are black.
In MATLAB R2014b and later you can set the 'GridColor' property of the axes to a desired value:
grid on
ax = gca;
ax.GridColor = [0.1, 0.1, 0.1]; % [R, G, B]
Please refer to the following documentation link:

  5 Comments

Show 2 older comments

Sign in to comment.

More Answers (4)

Image Analyst
Image Analyst on 13 Aug 2016
To do it in R2014b and later, try this:
y = sin([1:40]/10);
plot(y, 'm*-');
grid on;
ax = gca % Get handle to current axes.
ax.XColor = 'r'; % Red
ax.YColor = 'b'; % Blue
ax.GridAlpha = 0.9; % Make grid lines less transparent.
ax.GridColor = [0.1, 0.7, 0.2]; % Dark Green.

  0 Comments

Sign in to comment.


Jos (10584)
Jos (10584) on 26 Feb 2014
People might be interested in creating their own grid using my GRIDXY function I submitted many years ago to the File Exchange. An example:
gridxy(get(gca,'xtick'),get(gca,'ytick'),'color',[.6 .6 .6],'linewidth',1)

  1 Comment

LEE
LEE on 19 Jul 2016
thanks! this way is useful and make gridx/y separate so 'gridxy(get(gca,'tick'),'color',[.95 .95 .95],'linewidth',1)'can not work can you make the command more concise.

Sign in to comment.


muhammed
muhammed on 7 Jul 2016
really. So, it is not possible to change gridline color to 2013 version !. I mean black and dotted way

  1 Comment

Sarang Kunte
Sarang Kunte on 14 Jul 2016
You can change the GridColor property of an 'axes' to change the color of the grid lines in MATLAB R2014b or later. For earlier versions the above mentioned workaround can be used.

Sign in to comment.


Products


Release

R2014a

Community Treasure Hunt

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

Start Hunting!

Translated by