To add gridlines in MATLAB, you access the Axes object of your plot and set the relevant grid properties (XGrid
, YGrid
, ZGrid
) to 'on'
.
Gridlines in MATLAB are typically displayed at the locations of the major tick marks on your axes. To make these gridlines visible, you need to access the properties of the Axes object for your current plot.
The primary way to control gridline visibility using the Axes object is by setting the following properties:
XGrid
: Controls gridlines along the x-axis.YGrid
: Controls gridlines along the y-axis.ZGrid
: Controls gridlines along the z-axis (for 3D plots).
You can set these properties to one of two values:
'on'
: Displays the gridlines for that axis.'off'
: Hides the gridlines for that axis (the default state in some plot types).
Accessing the Axes Object
You can get the Axes object for the current plot using the gca
(get current axes) command. Once you have the Axes object, you can use dot notation to set its properties.
Example: Displaying Gridlines
Here's an example demonstrating how to create a simple 2-D plot and display gridlines, specifically showing how to display them only in the y-direction, as described in the reference:
- Create your plot: Generate some data and create a plot (e.g., using
plot
,bar
,scatter
, etc.). - Get the current Axes object: Use
ax = gca;
. - Set the desired grid properties: Use
ax.Property = 'value';
.
% Create sample data
y = rand(10,1);
% Create a bar plot
bar(y)
% Get the current Axes object
ax = gca;
% Display grid lines only in the y direction
ax.XGrid = 'off'; % Ensure X grid is off
ax.YGrid = 'on'; % Turn Y grid on
% ax.ZGrid = 'off'; % Z grid is off by default for 2D plots
In this example, bar(y)
creates the plot. ax = gca;
retrieves the handle to the axes. ax.YGrid = 'on';
makes the horizontal gridlines (corresponding to the y-axis ticks) visible, while ax.XGrid = 'off';
ensures vertical gridlines are not shown.
By setting XGrid
, YGrid
, and ZGrid
to 'on'
or 'off'
on the Axes object, you can control which gridlines are displayed on your plot.