Open In App

Matplotlib.axes.Axes.grid() in Python

Last Updated : 19 Apr, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute.

matplotlib.axes.Axes.grid() Function

The Axes.grid() function in axes module of matplotlib library is used to Configure the grid lines.

Syntax: Axes.grid(self, b=None, which=’major’, axis=’both’, **kwargs)

Parameters: This method accept the following parameters.

  • b : This parameter is an optional parameter, whether to show the grid lines or not.
  • which : This parameter is also an optional parameter and it is the grid lines to apply the changes on.
  • axis :This parameter is also an optional parameter and it is the axis to apply the changes on.

Returns:This method does not return any value.

Below examples illustrate the matplotlib.axes.Axes.grid() function in matplotlib.axes:

Example 1:




# Implementation of matplotlib function   
import matplotlib.pyplot as plt
import numpy as np
     
fig, ax = plt.subplots()
ax.plot([1, 2, 3])
ax.grid()
ax.set_title('matplotlib.axes.Axes.grid() Example\n',
             fontsize = 12, fontweight ='bold')
plt.show()


Output:

Example 2:




# Implementation of matplotlib function
import numpy as np
import matplotlib.pyplot as plt
    
x = np.arange(-5, 5, 0.01)
y1 = -3 * x*x + 10 * x + 10
y2 = 3 * x*x + x
    
fig, [ax, ax1] = plt.subplots(2, 1
                              sharex = True)
  
ax.plot(x, y1, x, y2, color ='black')
ax.fill_between(x, y1, y2, where = y2 >y1,
                facecolor ='green',
                alpha = 0.8)
  
ax.fill_between(x, y1, y2, where = y2 <= y1, 
                facecolor ='black'
                alpha = 0.8)
  
ax.xaxis.grid(True, color ="black")
ax.set_title('matplotlib.axes.Axes.grid() \
Example\n\n Grid in X-axis',
             fontsize = 12, fontweight ='bold')
  
ax1.plot(x, y1, x, y2, color ='black')
ax1.fill_between(x, y1, y2, where = y2 >y1, 
                 facecolor ='green',
                 alpha = 0.8)
  
ax1.fill_between(x, y1, y2, where = y2 <= y1,
                 facecolor ='black'
                 alpha = 0.8)
  
ax1.yaxis.grid(True, color ="black")
ax1.set_title('Grid in y-axis',
             fontsize = 12, fontweight ='bold')
plt.show()


Output:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads