axes() method in Matplotlib is used to create a new Axes instance (i.e., a plot area) within a figure. This allows you to specify the location and size of the plot within the figure, providing more control over subplot layout compared to plt.subplot(). It's key features include:
Creates a new Axes at a specified position inside the figure.
Allows precise control of the Axes position using normalized figure coordinates.
Returns an Axes object for further customization and plotting.
Supports multiple Axes in a single figure for complex layouts.
plt.figure() creates a blank figure and plt.axes([0.1, 0.1, 0.8, 0.8]) adds a subplot positioned within it.
np.linspace(0, 10, 100) creates 100 points and np.sin(x) computes their sine values.
ax.plot(x, y) plots the sine wave.
Syntax
matplotlib.pyplot.axes(*args, **kwargs)
Parameters: The parameters can be passed in different ways:
1. Positional Argument rect: A list or tuple of 4 floats [left, bottom, width, height] and defines the position and size of the axes as fractions of the figure width and height, all values between 0 and 1.
left: The distance from the left side of the figure to the left side of the axes.
bottom: The distance from the bottom of the figure to the bottom of the axes.
width: The width of the axes.
height: The height of the axes.
2. Keyword Arguments (kwargs): A dictionary of additional keyword arguments to customize the Axes object. Some common keyword arguments include:
polar: A boolean value (True or False). If True, creates a polar plot.
facecolor: A color value to set the background color of the axes.
projection: A string specifying the projection type (e.g., 'polar').
Other Axes properties can also be passed as keyword arguments for further customization.
Returns: (Axes) An instance of matplotlib.axes.Axes (or a subclass like Axes3D) .The newly created Axes object which can be used to plot data and customize the plot.
Examples
Example 1: In this example we are creating multiple axes in one figure.
plt.figure() initializes a blank figure and plt.axes() adds two Axes objects (ax1 and ax2) with specified positions using normalized figure coordinates [left, bottom, width, height].
ax1 (left side) is 10% from left, 10% from bottom, 35% width, 80% height, and ax2 (right side) is 55% from left, 10% from bottom, 35% width, 80% height.
np.linspace(0, 10, 100) generates 100 evenly spaced x-values between 0 and 10.
Example 2: In this example, we are creating 3d axes