Plots in matplotlib
represent the visualization of a given data. These plots require numerous properties to enhance the visuals. One of these properties is the gridline
.
A gridline
is a series of intersecting straight lines that show axis division. Apart from data visualization tools like Microsoft Excel, pandas, powerbi, and so on, the matplot library (matplotlib
) also comes with several features. These features enhance and change the visualization (figure, plot, etc.) of a data set. In this shot, we’ll learn about the feature of matplotlib
that helps us set line properties of a gridline in a plot.
Before we proceed, let’s see how we can add a grid to a plot in matplotlib
The pyplot
module in matplotlib
has a grid()
function that adds a grid line to a plot.
The following example demonstrates the use of 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()
pyplot
module from the matplot library
numpy
module.numpy.array()
method.numpy.array()
method.pyplot.plot()
method.pyplot.title()
method.pyplot.xlabel()
method.pyplot.ylabel()
method.pyplot.grid()
function.pyplot.show()
method.The pyplot.grid()
function takes the following parameters:
color
: Specifies the color we want. For example, red
, green
, yellow
, black
, and so on.linestyle
- Specifies the style we want on the line. For example, dashed ’—‘
, solid ’-‘
, dashdot ’-.’
, and so on.linewidth
: specifies the grid line’s size. Positive integers are the values.This function is always written like the code below:
grid(color = 'color', linestyle = 'linestyle', linewidth = number).
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() function propertiesplt.grid(color = 'red', linestyle = '-', linewidth=5)plt.show()
The code above is similar to the first one with some minor changes:
pyplot.grid()
where the color
we chose is red
, linestyle = solid
, and the linewidth
of 5
for the grid.