Matplotlib.pyplot.grid() in Python
matplotlib.pyplot.grid() function in Matplotlib is used to toggle the visibility of grid lines in a plot. Grid lines help improve readability of a plot by adding reference lines at major and/or minor tick positions along the axes. Example:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1, 2, 3], [4, 5, 6])
plt.grid(True)
plt.show()
Output

Explanation: This code plots a basic line graph and enables the grid for both axes, making it easier to read the plot.
Syntax
matplotlib.pyplot.grid(b=None, which='major', axis='both', **kwargs)
Parameters:
Parameter | Type | Description |
---|---|---|
b | bool or None, optional | Turns grid on (True), off (False), or toggles (None). |
which | 'major', 'minor', 'both' | Specifies which grid lines to show. |
axis | 'both', 'x', 'y' | Selects which axis to draw the grid on. |
kwargs | Additional line properties | Customizes grid appearance (e.g., color, linewidth, linestyle). |
Returns: This function modifies the grid of the current Axes in-place, meaning it doesn't return anything but updates the plot's grid properties directly.
Examples
Example 1: In this example, we plot a sine wave and customize the grid lines by setting the grid to be dashed ('--'), with a red color and reduced opacity (alpha=0.5).
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
y = np.sin(x)
fig, ax = plt.subplots()
ax.plot(x, y)
plt.grid(True, linestyle='--', linewidth=0.7, color='red', alpha=0.5)
plt.show()
Output

Explanation: we generate a sine wave using np.sin(x) and plot it using Matplotlib. The grid is then customized to appear dashed, with a red color and semi-transparent effect (alpha=0.5), making it less intrusive on the plot.
Example 2: In this example, we plot a simple set of points and enable the grid only on the x-axis to focus on horizontal alignment.
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1, 2, 3], [1, 4, 9])
plt.grid(True, axis='x')
plt.show()
Output

Explanation: We create a simple plot with points [1, 2, 3] on the x-axis and [1, 4, 9] on the y-axis. The grid is then enabled only on the x-axis by setting axis='x'. This ensures that only the horizontal grid lines are shown, making the x-axis positioning clearer.
Example 3: In this example, we plot a quadratic curve and enable grid lines for both the x and y axes. The grid lines are set to be solid, green and thicker for better visibility.
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
x = [0, 1, 2, 3, 4]
y = [0, 1, 4, 9, 16]
ax.plot(x, y)
plt.grid(True, which='major', axis='both', linestyle='-', color='green', linewidth=1.5)
plt.show()
Output

Explanation: We plot a quadratic curve with x-values [0, 1, 2, 3, 4] and their squares for y-values. The grid is customized to be solid, green and thicker (linewidth=1.5), enabled for both axes to enhance readability.