Matplotlib 简明教程

Matplotlib - Axes Class

在 Matplotlib 的上下文中, axes 并不指轴的复数形式。相反,它代表图形或画布上的整个绘图区域。其中包括 x 轴、y 轴、绘图数据、刻度线、刻度线标签等。

In the context of Matplotlib, axes does not refer to the plural form of an axis. Instead, it represents the entire plotting area on a figure or canvas. Which includes the x-axis, y-axis, plotting data, ticks, ticks labels, and more.

参考下图 -

Refer to the image below −

axes class intro

考虑在其中使用 ax = fig.subplots() 方法创建两个 Axes 对象的图形。第一组轴显示指数数据,而第二组轴显示正弦波。每个 Axes(子图)都有自己的一组标签、刻度和图例,在同一个图形中提供不同的表示。

Consider the figure where two Axes objects are created using the ax = fig.subplots() method. The first axes display exponential data, while the second axes show a sine wave. Each Axes (subplot) has its own set of labels, ticks, and legends, providing a distinct representation within the same figure.

Axes class in matplotlib

Axes() class 用作创建数据可视化的网关。在图形上实例化一个 Axes 对象后,将有各种方法可用于在该绘图区域内添加和操作数据。

The Axes() class serves as the gateway to creating data visualizations. Once an Axes object is instantiated on a figure, a variety of methods become available to add and manipulate data within that plotting area.

此类是 matplotlib.axes 模块的一部分,提供了使用 Matplotlib 面向对象编程 (OOP) 界面的基本功能。最重要的绘图方法大部分都在 Axes 类上定义,使其成为自定义和增强可视化的核心组件。

This class is part of the matplotlib.axes module, providing fundamental functionalities to work with the Matplotlib object-oriented programming (OOP) interface. Most of the essential plotting methods are defined on the Axes class, making it a central component for customizing and enhancing visualizations.

Creating an Axes

创建 Axes 对象通常是 Matplotlib 绘图中的第一步。这可以完成 Figure 对象上的方法,如 Figure.subplots()Figure.add_axes() ,或通过 pyplot 接口函数 pyplot.subplots() 。这些方法可用于在图形中创建单个或多个 Axes 对象。

Creating an Axes object is typically the first step in Matplotlib plotting. This can be done through methods on Figure object like Figure.subplots(), Figure.add_axes(), or via the pyplot interface function, pyplot.subplots(). These methods provides the creation of one or more Axes objects in a figure.

Example

以下示例使用 pyplot.subplot() 方法在图形上创建两个坐标轴。subplots()方法可用于生成坐标轴实例。

The following example uses the pyplot.subplot() method to creat two axes on a figure. The subplots() method is useful for generating the axes instance.

import matplotlib.pyplot as plt
import numpy as np

# Creating a 1x2 subplot layout
fig, (axes1, axes2)  = plt.subplots(1, 2, figsize=(7, 4),
   layout="constrained")

# Adding labels to each subplot
axes1.annotate('axes1', (0.5, 0.5),transform=axes1.transAxes,
   ha='center', va='center', fontsize=18,
   color='darkgrey')

axes2.annotate('axes2', (0.5, 0.5),transform=axes2.transAxes,
   ha='center', va='center', fontsize=18,
   color='darkgrey')

fig.suptitle('Creating Two Axes on a Figure')

# Displaying the plot
plt.show()

执行上述代码,我们将得到以下输出 −

On executing the above code we will get the following output −

axes class ex1

Changing an Axes properties

若要设置坐标轴的属性,您必须访问坐标轴对象,然后可以使用各种 set_* 方法修改其属性。

To set the properties of an axes, you have to access the axes object, after that you can use various set_* methods to modify its properties.

Example

import matplotlib.pyplot as plt
import numpy as np

# Creating a 1x2 subplot layout
fig, (axes1, axes2) = plt.subplots(1, 2, figsize=(7, 4),
   constrained_layout=True)

# Changing the properties of the first axes
axes1.set_xlabel("X-axis")        # Set label for X-axis
axes1.set_ylabel("Y-axis")        # Set label for Y-axis
axes1.set_facecolor('lightgreen') # Setting background color
axes1.annotate('axes1', (0.5, 0.5), transform=axes1.transAxes,
   ha='center', va='center', fontsize=18,
   color='darkgrey')
axes2.set_title('Second axes')
axes2.annotate('axes2', (0.5, 0.5), transform=axes2.transAxes,
   ha='center', va='center', fontsize=18,
   color='darkgrey')

# Adding a title to the figure
fig.suptitle('Changing Axes Properties')

# Displaying the plot
plt.show()

执行上述代码时,您将获得以下输出 -

On executing the above code you will get the following output −

axes class ex4

Plotting on an Axes

该类提供了多种高级绘图方法,用于在坐标轴上创建不同的绘图。

This class offers several high-level plotting methods to create different plot on axes.

Example

这是一个示例,使用 Axes.plot() 方法创建表示 sin(x) 的折线图。

Here is an example uses the Axes.plot() method to create a line plot representing the sin(x).

import matplotlib.pyplot as plt
import numpy as np

# Sample Data
x = np.linspace(0, 2 * np.pi, 400)
y = np.sin(x**2)

# Create subplots
fig, axs = plt.subplots(figsize=(7,4))

# Draw the plot
axs.plot(x, y)

# Show the plot
plt.show()

执行上述代码,我们将得到以下输出 −

On executing the above code we will get the following output −

axes class ex2

Customizing the axes Data

Axes 对象包含大部分图形元素,例如 Axis、Tick、Line2D、Text、Polygon 等,并设置坐标系统。可以通过向 Axes 添加标签、标题、图例和注释来自定义这些元素,以增强可视化清晰度。

The Axes object contains most of the figure elements such as Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. These elements can be customized by adding labels, titles, legends, and annotations to the Axes enhances the clarity of visualizations.

Example

这是一个简单示例,向 Axes 添加标签、标题和图例。

Here is a simple example that adds the labels, titles, legends to an Axes.

import matplotlib.pyplot as plt
import numpy as np

# Sample Data
x = np.linspace(0, 2 * np.pi, 400)
y = np.sin(x**2)

# Create subplots
fig, axs = plt.subplots(figsize=(7,4))

# Draw the plot
axs.plot(x, y, label='Sin(x)')

# Add titles
axs.set_title('Sin Plot')

# Add X and Y labels
axs.set_xlabel('X-axis')
axs.set_ylabel('Y-axis')

# Add legend
axs.legend()

# Show the plot
plt.show()

执行上述代码,我们将得到以下输出 −

On executing the above code we will get the following output −

axes class ex3

Clearing the Axes

若要清除坐标轴的内容,可以使用 axes.cla()axes.clear() 方法。

To clear the contents of an axes, you can use the axes.cla() or axes.clear() method.

Example

这是一个示例,展示了如何清除子图中的第一个坐标轴。

Here is an example that show how you can clear the first axes in a subplot.

import matplotlib.pyplot as plt
import numpy as np

# Sample data
x = np.linspace(-1, 1, 10)
y = np.exp(x)

# Creating subplots
fig, (axes1, axes2) = plt.subplots(1, 2, figsize=(7, 4),
   constrained_layout=True)

# Plotting on the first axes
axes1.plot(x, y, c='red')
axes1.set_xlabel("X-axis")        # Set label for X-axis
axes1.set_ylabel("Y-axis")        # Set label for Y-axis
axes1.set_facecolor('lightgreen') # Setting background color
axes1.annotate('axes1', (0.5, 0.5), transform=axes1.transAxes,
   ha='center', va='center', fontsize=18,
   color='darkgrey')

# Adding a title to the second axes
axes2.set_title('Second axes')
axes2.annotate('axes2', (0.5, 0.5), transform=axes2.transAxes,
   ha='center', va='center', fontsize=18,
   color='darkgrey')

# Clearing the first axes
axes1.cla()

# Adding a title to the figure
fig.suptitle('Clearing the Axes')

# Displaying the plot
plt.show()

执行上述代码时,您将获得以下输出 -

On executing the above code you will get the following output −

axes class ex5