除非您的函数签名必须保持示例中定义的那样,否则在函数外部创建子图并传递适当的函数会更容易Axes
每个函数的实例。
def plot_fig_1(vars, args, ax):
# do something
ax.plot(x, y)
def plot_fig_2(vars, args, ax):
# do something
ax.plot(x, y)
fig, ax = plt.subplots(2, 1, sharex=True)
plot_fig_1(..., ax[0])
plot_fig_2(..., ax[1])
如果您需要创建一个仅包含其中一个子图的图形,您可以使用以下命令来执行此操作:
fig, ax = plt.subplot()
plot_fig_1(..., ax)
或者,如果函数需要独立,请给出ax
参数一个默认值并在函数内测试它。
def plot_fig_1(vars, args, ax=None):
if ax is None:
fig, ax = plt.subplot()
# do something
ax.plot(x, y)