0
0
MatlabHow-ToBeginner ยท 3 min read

How to Add Grid in MATLAB Plots Easily

In MATLAB, you add grid lines to a plot by using the grid on command. This command turns on the grid lines, making it easier to read values on the plot. To remove grid lines, use grid off.
๐Ÿ“

Syntax

The basic syntax to control grid lines in MATLAB plots is:

  • grid on: Turns on the grid lines.
  • grid off: Turns off the grid lines.
  • grid toggle: Switches the grid state between on and off.

You use these commands after creating a plot to control the grid visibility.

matlab
grid on
% Turns on grid lines on the current plot

grid off
% Turns off grid lines on the current plot

grid toggle
% Toggles grid lines on or off
๐Ÿ’ป

Example

This example shows how to plot a simple sine wave and add grid lines to improve readability.

matlab
x = linspace(0, 2*pi, 100);
y = sin(x);
plot(x, y)
grid on
xlabel('x values')
ylabel('sin(x)')
title('Sine Wave with Grid')
Output
A plot window opens showing a sine wave curve with grid lines visible behind the curve.
โš ๏ธ

Common Pitfalls

Some common mistakes when adding grids in MATLAB include:

  • Calling grid on before creating a plot, which may not show the grid if no plot exists yet.
  • Using grid on but the plot axes are not visible or customized, making the grid hard to see.
  • For multiple subplots, forgetting to activate grid on each subplot separately.

Always call grid on after plotting and check subplot contexts.

matlab
subplot(1,2,1)
plot(x, y)
grid on

subplot(1,2,2)
plot(x, cos(x))
% Forgot grid on here, so no grid lines on second plot

% Correct way:
subplot(1,2,2)
plot(x, cos(x))
grid on
๐Ÿ“Š

Quick Reference

CommandDescription
grid onShow grid lines on current plot
grid offHide grid lines on current plot
grid toggleSwitch grid lines on or off
grid minorShow minor grid lines (for finer grid)
โœ…

Key Takeaways

Use grid on after plotting to add grid lines to your MATLAB plot.
For multiple subplots, enable grid on each subplot individually.
Use grid off to remove grid lines when not needed.
Grid lines improve plot readability by showing reference lines behind data.
Remember to call grid commands after creating the plot for them to take effect.