共同点
Both, add_axes https://matplotlib.org/stable/api/figure_api.html#matplotlib.figure.Figure.add_axes and add_subplot https://matplotlib.org/stable/api/figure_api.html#matplotlib.figure.Figure.add_subplot向图形添加轴。他们都返回一个(a的子类)matplotlib.axes.Axes
object.
然而,用于添加轴的机制有很大不同。
add_axes
的呼叫签名add_axes https://matplotlib.org/stable/api/figure_api.html#matplotlib.figure.Figure.add_axes is add_axes(rect)
, where rect
是一个列表[x0, y0, width, height]
表示图形坐标中新轴的左下点(x0,y0)
及其宽度和高度。因此轴位于画布上的绝对坐标中。例如。
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
在画布中放置一个与画布本身一样大的图形。
add_subplot
的呼叫签名add_subplot https://matplotlib.org/stable/api/figure_api.html#matplotlib.figure.Figure.add_subplot不直接提供将轴放置在预定义位置的选项。它允许根据子图网格指定轴的位置。指定此位置的常用且最简单的方法是 3 整数表示法,
fig = plt.figure()
ax = fig.add_subplot(231)
在此示例中,在第一个位置 (1
)在 2 行 3 列的网格上。仅生产单个轴,add_subplot(111)
将使用(1 x 1 子图网格上的第一个图)。 (在较新的 matplotlib 版本中,add_subplot()
没有任何参数也是可能的。)
这种方法的优点是 matplotlib 负责精确定位。默认情况下add_subplot(111)
会产生一个位于[0.125,0.11,0.775,0.77]
或类似的,它已经在轴周围为标题和(勾号)标签留下了足够的空间。然而,这个位置也可能会根据情节中的其他元素、标题集等而改变。
也可以使用调整pyplot.subplots_adjust(...)
or pyplot.tight_layout()
.
在多数情况下,add_subplot
将是在画布上创建绘图轴的首选方法。仅在精确定位很重要的情况下,add_axes
可能有用。
Example
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = (5,3)
fig = plt.figure()
fig.add_subplot(241)
fig.add_subplot(242)
ax = fig.add_subplot(223)
ax.set_title("subplots")
fig.add_axes([0.77,.3,.2,.6])
ax2 =fig.add_axes([0.67,.5,.2,.3])
fig.add_axes([0.6,.1,.35,.3])
ax2.set_title("random axes")
plt.tight_layout()
plt.show()
选择
获取一个或多个子图及其句柄的最简单方法是plt.subplots() https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.subplots.html。对于一个轴,使用
fig, ax = plt.subplots()
或者,如果需要更多子图,
fig, axes = plt.subplots(nrows=3, ncols=4)
最初的问题
In the 使用放置轴fig.add_axes([0,0,1,1])
,使其紧贴图形边界。这样做的缺点当然是刻度、刻度标签、轴标签和标题被切断。因此我在答案的评论之一中建议使用fig.add_subplot
因为这将自动为这些元素留出足够的空间,如果这还不够,可以使用进行调整pyplot.subplots_adjust(...)
or pyplot.tight_layout()
.