How to add grid lines to a plot in matplotlib

Overview

Plots in matplotlib are used to represent the visualization of a given data. These plots require a lot of properties which are required and are used to enhance the look of the visuals. One of these properties is the gridline.

A gridline is simply a series of intersecting straight or curved lines used to show axis division. Interestingly, order than other data visualization tools like Microsoft excel, pandas, powerbi e.t.c., the matplot library (matplotlib) also comes with many features that help enhance and add changes to the visualization(figure, plot e.t.c) of a data set. In this shot, we want to see the feature of matplotlib that helps us add a grid line to a plot.

Adding grid lines to a plot

The pyplot module in matplotlib has a function called grid() which is used to add a grid line to a plot.

Example

Now let us use the pyplot.grid() to add a grid to a plot:

import matplotlib.pyplot as plt
import numpy as np
x= np.array([1, 5])
y = np.array([10, 20])
plt.plot(x, y)
# usig the title() method
plt.title('Y against X')
# using the xlabel() and ylabel() methods
plt.xlabel("x axis")
plt.ylabel("y axis")
# adding the grid using the grid() function
plt.grid()
plt.show()
Output of the code

• Line 1: we imported the pyplot module from the matplot library

  • Line2: we imported the numpy module
  • Line 4: we created an array variable x using the numpy.array() method.
  • Line 5: we created another array variable y using the numpy.array() method.
  • Line 7: using the pyplot.plot() method we plotted the y against x (that is x on the x-axis and y on the y-axis.
  • Line 10: Line 10: using the pyplot.title() method, we gave a title to our plot.
  • Line 12: using the pyplot.xlabel() method, we gave a label to the x-axis of our plot.
  • Line 13: using the pyplot.ylabel() method, we gave a label to the y-axis of our plot.
  • line 15: using the pyplot.grid() function, we added a grid to the plot.
  • Line 16: using the pyplot.show() method, we asked python to show us our plot.

Specifying the grid axis

Interestingly, we can specify which axis our grid line should appear. In this case, the pyplot.grid() takes a parameter axis which takes x or y value to specify which of the axis you would like to see the grid.

Example

Now, let’s create a plot to show the grid on the x-axis only:

import matplotlib.pyplot as plt
import numpy as np
x= np.array([1, 5])
y = np.array([10, 20])
plt.plot(x, y)
# usig the title() method
plt.title('Y against X')
# using the xlabel() and ylabel() methods
plt.xlabel("x axis")
plt.ylabel("y axis")
# to display the grid on the x axis
plt.grid(axis='x')
plt.show()
Output of the code

Free Resources