How can I display gridlines on my matplotlib plots?

Gridlines are horizontal and vertical lines that are used as a visual aid in plotting graphs or charts. They help in providing a better understanding of the data and the overall structure of the plot. In order to display gridlines on matplotlib plots, one can use the “grid()” function which is provided by the matplotlib library. This function allows the user to specify the style and color of the gridlines, as well as the spacing between them. By using this function, the user can easily add gridlines to their matplotlib plots, making them more visually appealing and easier to interpret.

Show Gridlines on Matplotlib Plots


By default, Matplotlib does not display gridlines on plots. However, you can use the matplotlib.pyplot.grid() function to easily display and customize gridlines on a plot.

This tutorial shows an example of how to use this function in practice.

Basic Scatterplot in Matplotlib

The following code shows how to create a simple scatterplot using Matplotlib:

import matplotlib.pyplot as plt

#create data
x = [1, 2, 3, 4, 5]
y = [20, 25, 49, 88, 120]

#create scatterplot of data
plt.scatter(x, y)
plt.show()

Add Gridlines to Both Axes

To add gridlines to the plot, we can simply use the plt.grid(True) command:

import matplotlib.pyplot as plt

#create data
x = [1, 2, 3, 4, 5]
y = [20, 25, 49, 88, 120]

#create scatterplot of data with gridlines
plt.scatter(x, y)
plt.grid(True)
plt.show()

Matplotlib plot with gridlines

Add Gridlines to Only One Axis

We can use the axis argument to only add gridlines to the x-axis:

import matplotlib.pyplot as plt

#create data
x = [1, 2, 3, 4, 5]
y = [20, 25, 49, 88, 120]

#create scatterplot of data with gridlines
plt.scatter(x, y)
plt.grid(axis='x')
plt.show()

Matplotlib gridlines on only one axis

Or only the y-axis:

import matplotlib.pyplot as plt

#create data
x = [1, 2, 3, 4, 5]
y = [20, 25, 49, 88, 120]

#create scatterplot of data with gridlines
plt.scatter(x, y)
plt.grid(axis='y')
plt.show()

Matplotlib plot with y-axis gridlines

Customize Gridlines

We can also customize the appearance of the gridlines using the plt.rc() function:

import matplotlib.pyplot as plt

#create data
x = [1, 2, 3, 4, 5]
y = [20, 25, 49, 88, 120]

#create scatterplot of data with gridlines
plt.rc('grid', linestyle=':', color='red', linewidth=2)
plt.scatter(x, y)
plt.grid(True)
plt.show()

Customized gridlines in Matplotlib

You can find a complete list of ways to customize the gridlines in the Matplotlib documentation.

Additional Resources

The following tutorials explain how to perform other common tasks in Matplotlib:

How to Remove Ticks from Matplotlib Plots
How to Change Font Sizes on a Matplotlib Plot

x