Matplotlib.axes.Axes.add_patch() in Python
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.add_patch() Function
The Axes.add_patch() function in axes module of matplotlib library is used to add a Patch to the axes’ patches; return the patch.
Syntax: Axes.add_patch(self, p)
Parameters: This method accepts the following parameters.
- line: This parameter is the Patch to the axes’ patches.
Return value: This method returns the Patch .
Below examples illustrate the matplotlib.axes.Axes.add_patch() function in matplotlib.axes:
Example 1:
# Implementation of matplotlib function import numpy as np import matplotlib.pyplot as plt y, x = np.mgrid[: 5 , 1 : 6 ] poly_coords = [ ( 0.25 , 2.75 ), ( 3.25 , 2.75 ), ( 2.25 , 0.75 ), ( 0.25 , 0.75 ) ] fig, ax = plt.subplots() cells = ax.plot(x, y, x + y, color = 'green' ) ax.add_patch( plt.Polygon(poly_coords, color = 'forestgreen' , alpha = 0.5 ) ) ax.margins(x = 0.1 , y = 0.05 ) ax.set_aspect( 'equal' ) fig.suptitle('matplotlib.axes.Axes.add_patch() \ function Example\n\n', fontweight = "bold" ) plt.show() |
Output:
Example 2:
# Implementation of matplotlib function import matplotlib.path as mpath import matplotlib.patches as mpatches import matplotlib.pyplot as plt Path = mpath.Path fig, ax = plt.subplots() pp1 = mpatches.PathPatch( Path([( 0 , 0 ), ( 1 , 0 ), ( 1 , 1 ), ( 0 , 0 )], [Path.MOVETO, Path.CURVE3, Path.CURVE3, Path.CLOSEPOLY]), fc = "none" , transform = ax.transData) ax.add_patch(pp1) ax.plot([ 0.75 ], [ 0.25 ], "go-" ) fig.suptitle('matplotlib.axes.Axes.add_patch() \ function Example\n\n', fontweight = "bold" ) plt.show() |
Output: