10.7 C
London
Sunday, July 7, 2024
HomePythonMatplotlib in PythonHow to Show Gridlines on Matplotlib Plots

How to Show Gridlines on Matplotlib Plots

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

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

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories