Grids are made up of intersecting straight (vertical, horizontal, and angular) or curved lines used to structure our content. Matplotlib helps us to draw plain graphs but it is sometimes necessary to use grids for better understanding and get a reference for our data points. Thus, Matplotlib provides a grid() for easy creation of gridlines with tonnes of customization.
The grid() function in the Pyplot module of the Matplotlib library is used to configure the grid lines.
Syntax: matplotlib.pyplot.grid(True, color = “grey”, linewidth = “1.4”, axis = ”Y”, linestyle = “-.”)
Add Grid Lines to a Plot
The grid() sets the visibility of grids by specifying a boolean value (True/False). We can also choose to display minor or major ticks or both. Also, color, linewidth ,and lifestyle can be changed as additional parameters.
Python3
import matplotlib.pyplot as plt
import numpy as np
x1 = np.linspace( 0.0 , 5.0 )
y1 = np.cos( 2 * np.pi * x1) * np.exp( - x1)
fig, (ax1, ax2) = plt.subplots( 1 , 2 , figsize = ( 12 , 5 ))
ax1.plot(x1, y1)
ax1.set_title( 'Plot without grid' )
ax2.plot(x1, y1)
ax2.set_title( "Plot with grid" )
ax2.grid( True )
plt.show()
|
Output:
Set Line Properties for the Grid
Now let’s draw gridlines using extra line properties such as color, linestyle, and linewidth.
Python3
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace( 0 , 2 * np.pi, 400 )
y = np.sin(x * * 2 )
plt.plot(x, y, 'green' )
plt.title( "Plot with linewidth and linestyle" )
plt.grid( True , color = "grey" , linewidth = "1.4" , linestyle = "-." )
plt.show()
|
Output:
Specify Which Grid Lines to Display
Display only grid lines for the x-axis
Draw gridlines using axis=’x’.
Python3
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace( 0 , 2 * np.pi, 400 )
y = np.sin(x * * 2 )
plt.plot(x, y, 'green' )
plt.title( "Plot with linewidth and linestyle" )
plt.grid( True , color = "grey" , linewidth = "1.4" ,axis = 'x' )
plt.show()
|
Output:
Display only grid lines for the y-axis
Draw gridlines using axis=’y’.
Python3
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace( 0 , 2 * np.pi, 400 )
y = np.sin(x * * 2 )
plt.plot(x, y, 'green' )
plt.title( "Plot with linewidth and linestyle" )
plt.grid( True , color = "grey" , linewidth = "1.4" , axis = 'y' )
plt.show()
|
Output:
Last Updated :
08 Sep, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...