Matplotnib axes class
The Axes class in Matplotlib is a key component that represents an individual plot within a figure. It provides methods and attributes for customizing and manipulating various aspects of the plot, such as the axes limits, labels, ticks, grids, and more.
To create an Axes object, you typically start by creating a Figure object using plt.figure(). Then, you can add one or more Axes objects to the figure using the add_subplot() or add_axes() methods. The add_subplot() method divides the figure into a grid of subplots, and add_axes() allows you to specify the position and size of the axes within the figure.
import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(1, 1, 1)
The Axes object provides various methods and attributes to customize its properties. Some common properties you can modify include:
- Axes labels: Use set_xlabel() and set_ylabel() methods to set the x-axis and y-axis labels, respectively.
- Axes title: Use the set_title() method to set the title of the axes.
- Axes limits: Use set_xlim() and set_ylim() methods to set the x-axis and y-axis limits, respectively.
- Ticks and tick labels: Use set_xticks(), set_yticks(), set_xticklabels(), and set_yticklabels() methods to customize the positions and labels of ticks.
- Grid lines: Use grid() method to toggle the grid lines on or off.
- Legend: Use legend() method to add a legend to the plot.
ax.set_xlabel('X-axis') ax.set_ylabel('Y-axis') ax.set_title('Plot Title') ax.set_xlim(0, 6) ax.set_ylim(0, 12) ax.grid(True) ax.legend()
You can create multiple Axes objects within a single Figure to create subplots or arrange plots in a grid layout. The add_subplot() method is commonly used to create multiple subplots, while add_axes() allows more control over the position and size of each axes.
fig = plt.figure() ax1 = fig.add_subplot(2, 2, 1) # Creates a 2x2 grid of subplots, select the first one ax2 = fig.add_subplot(2, 2, 2) # Select the second subplot ax3 = fig.add_axes([0.6, 0.2, 0.3, 0.4]) # Creates a custom-sized axes
import matplotlib.pyplot as pyplot import numpy as np G = np.linspace(-np.pi, np.pi, 18) K = np.cos(G) S = np.sin(G) ax = pyplot.axes([0.1, 0.1, 0.8, 0.8]) # 'bs:' mentions blue color, square # marker with dotted line. ax1 = ax.plot(G, K, 'r+:') #'ro-' mentions red color, circle # marker with solid line. ax2 = ax.plot(G, S, 'd') ax.legend(labels = ('Cosine Data points', 'Sine Data points'), loc = 'lower right') ax.set_title("Basic Trig - Functions") pyplot.show()
Marker | Code |
---|---|
Point | '.' |
Circle | 'o' |
Cross | 'x' |
Diamond | 'D' |
Hexagon | 'H' |
Square | 's' |
Plus | '+' |
import matplotlib.pyplot as pyplot import numpy as np X = np.linspace(-np.pi, np.pi, 25) C = np.cos(X) S = np.sin(X) ax = pyplot.axes([0.1, 0.1, 0.8, 0.8]) ax1 = ax.plot(X, C, 'cx-.') ax2 = ax.plot(X, S, 'bD:') ax.legend(labels = ('Wave 1', 'wave 2'), loc = 'lower right') ax.set_title("Sample Wavelenthss") pyplot.show()
Комментарии
Отправить комментарий