Hey coder! In this tutorial, we’ll learn how to add gridlines on the basic Matplotlib plots we generally plot. We will be making use of the Matplotlib
library is a python that comes with an interactive environment for creating scientific plots and graphs.
Also Read: Python Matplotlib
A gridline
is simply a series of intersecting straight or curved lines used to show axis division. They are lines that cross the chart plot to show axis divisions and help viewers of the chart see what value is represented by an unlabeled data point.
Let’s not wait any more time, and dive right into the code implementation.
Code Implementation of Adding Gridlines
The pyplot
module in matplotlib
has a function called grid()
which can add a grid line
to the plot in the later sections plot. To create the dataset, we will be creating 5 random x values and computing y values for the x values we get.
import matplotlib.pyplot as plt
import numpy as np
x= np.random.randint(1,10,5)
y = [i*2+4 for i in x]
Let us plot a simple plot with no grid lines available using the code below. We will add title, x, and y-axis labels for the final plot.
plt.figure(facecolor='w')
plt.plot(x, y)
plt.title('y = 2*x + 4')
plt.xlabel("x values")
plt.ylabel("y values")
plt.show()

The next thing that we aim to do is add grid lines to the image we see above this text. All you have to do is add the grid
function before displaying the plot. The code for the same is shown below.
plt.figure(facecolor='w')
plt.plot(x, y)
plt.title('y = 2*x + 4')
plt.xlabel("x values")
plt.ylabel("y values")
plt.grid()
plt.show()

Using the axis
parameter in the grid function, we can specify which grid lines to display. By default, both the grid lines come into play. Look at the code and output below.
plt.figure(facecolor='w')
plt.plot(x, y)
plt.title('y = 2*x + 4')
plt.xlabel("x values")
plt.ylabel("y values")
plt.grid(axis='x')
plt.show()

plt.figure(facecolor='w')
plt.plot(x, y)
plt.title('y = 2*x + 4')
plt.xlabel("x values")
plt.ylabel("y values")
plt.grid(axis='y')
plt.show()

We can set the properties of the grid in various ways for color, style, and much more using the code below.
plt.figure(facecolor='w')
plt.plot(x, y,color='green')
plt.title('y = 2*x + 4')
plt.xlabel("x values")
plt.ylabel("y values")
plt.grid(color = 'violet', linestyle = '--', linewidth = 0.75)
plt.show()

Conclusion
Congratulations! Now you know how to add gridlines in Python using the matplotlib library. Keep reading to learn more!
I would recommend you to have a read of the following tutorials as well: