Matplotlib - Display grid only along X-axis


Matplotlib - Display grid only along X-axis

In Matplotlib, you can choose to display only the grid along the X-axis.

To display grid only along the X-axis, call the grid() function from matplotlib.pyplot and pass 'x' as the argument for the axis parameter. For example, plt.grid(axis='x') displays the grid only along the X-axis.

import matplotlib.pyplot as plt
plt.grid(axis='x')

Example for Grid along X-axis

In the following program, we shall display a plot with a line, and display grid along only X-axis using grid() function.

Python Program

import matplotlib.pyplot as plt

# Example data
x = [1, 2, 3, 4, 5]
y = [10, 20, 25, 55, 40]

# Plot the data
plt.plot(x, y, marker='o')

# Add a grid to the plot only along X-axis
plt.grid(axis='x')

# Show the plot
plt.show()

Output

Matplotlib - Display grid only along X-axis
Grid along X-axis