在 Python 中,ax 通常是 Matplotlib 库中 Axes 对象的缩写。Axes 是 Matplotlib 中用于绘制图表的核心对象,它代表了一个独立的绘图区域(例如一个子图)。
什么是 ax?
ax是Axes实例的常见变量名。- 它包含了图表的所有元素:坐标轴、标题、标签、数据系列等。
- 通过
ax,你可以控制图表的几乎所有方面。
基本用法示例
示例 1:创建单个子图
import matplotlib.pyplot as plt
import numpy as np
# 生成数据
x = np.linspace(0, 10, 100)
y = np.sin(x)
# 创建图形和轴
fig, ax = plt.subplots()
# 在 ax 上绘图
ax.plot(x, y, label='sin(x)')
和标签
ax.set_title('Sine Wave')
ax.set_xlabel('x')
ax.set_ylabel('sin(x)')
# 显示图例
ax.legend()
# 显示图表
plt.show()
示例 2:创建多个子图
import matplotlib.pyplot as plt
import numpy as np
# 生成数据
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
# 创建 1 行 2 列的子图
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4))
# 第一个子图
ax1.plot(x, y1, 'r-', label='sin(x)')
ax1.set_title('Sine')
ax1.legend()
# 第二个子图
ax2.plot(x, y2, 'b-', label='cos(x)')
ax2.set_title('Cosine')
ax2.legend()
# 自动调整布局并显示
plt.tight_layout()
plt.show()
常用 ax 方法
| 方法 | 说明 |
|---|---|
ax.plot() |
绘制折线图 |
ax.bar() |
绘制柱状图 |
ax.scatter() |
绘制散点图 |
ax.set_title() |
|
ax.set_xlabel() |
设置 x 轴标签 |
ax.set_ylabel() |
设置 y 轴标签 |
ax.legend() |
显示图例 |
ax.grid() |
显示网格 |
ax.set_xlim() / ax.set_ylim() |
设置坐标轴范围 |
ax.text() |
在图上添加文本 |
ax.annotate() |
添加注释 |
与 plt 的区别
plt是pyplot模块,提供 MATLAB 风格的接口,适合简单绘图。ax是Axes对象,提供更精细的控制,适合复杂图表或多子图布局。
推荐做法:在复杂项目中,优先使用 fig, ax = plt.subplots() 的方式,而不是直接使用 plt.plot() 等函数。
常见问题
Q: 如何修改坐标轴刻度?
ax.set_xticks([0, 2, 4, 6, 8, 10]) ax.set_xticklabels(['A', 'B', 'C', 'D', 'E', 'F'])
Q: 如何添加注释?
ax.annotate('Peak', xy=(np.pi/2, 1), xytext=(np.pi, 1.5),
arrowprops=dict(facecolor='black', shrink=0.05))
Q: 如何保存图表?
fig.savefig('my_plot.png', dpi=300, bbox_inches='tight')
首发原创文章,作者:世雄 - 原生数据库架构专家,如若转载,请注明出处:https://idctop.com/article/482412.html



