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()
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()
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()
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()
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