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.
grid lines to a plotThe pyplot module in matplotlib has a function called grid() which is used to add a grid line to a plot.
Now let us use the pyplot.grid() to add a grid to a plot:
import matplotlib.pyplot as pltimport numpy as npx= np.array([1, 5])y = np.array([10, 20])plt.plot(x, y)# usig the title() methodplt.title('Y against X')# using the xlabel() and ylabel() methodsplt.xlabel("x axis")plt.ylabel("y axis")# adding the grid using the grid() functionplt.grid()plt.show()
• Line 1: we imported the pyplot module from the matplot library
numpy modulex using the numpy.array() method.y using the numpy.array() method.pyplot.plot() method we plotted the y against x (that is x on the x-axis and y on the y-axis.pyplot.title() method, we gave a title to our plot.pyplot.xlabel() method, we gave a label to the x-axis of our plot.pyplot.ylabel() method, we gave a label to the y-axis of our plot.pyplot.grid() function, we added a grid to the plot.pyplot.show() method, we asked python to show us our plot.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.
Now, let’s create a plot to show the grid on the x-axis only:
import matplotlib.pyplot as pltimport numpy as npx= np.array([1, 5])y = np.array([10, 20])plt.plot(x, y)# usig the title() methodplt.title('Y against X')# using the xlabel() and ylabel() methodsplt.xlabel("x axis")plt.ylabel("y axis")# to display the grid on the x axisplt.grid(axis='x')plt.show()