python - 将数字添加到子图

标签 python matplotlib subplot

我是 matplotlib 的新手,正在尝试了解如何将数字添加到子图中。

我有三个不同的函数,它们输出一个数字:

def plot_fig_1(vars, args):
    f, ax, put.subplots()
    # do something
    ax.plot(x, y)
    return f, ax


def plot_fig_2(vars, args):
    f, ax, put.subplots()
    # do something
    ax.plot(x, y)
    return f, ax

现在,例如,我想将两个图形合并到具有共享 X 轴的单个图中。我尝试过:

f_1, ax_1 = plot_fig_1(...)
f_2, ax_2 = plot_fig_2(...)

new_fig, new_ax = plt.subplots(2,1)
new_ax[0] = f_1
new_ax[1] = f_2

在这里我基本上迷失了。我正在阅读 Matplotlib 手册,但到目前为止还没有运气。

最佳答案

除非您的函数签名必须保持示例中定义的那样,否则在函数外部创建子图并将适当的 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)

关于python - 将数字添加到子图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50279217/

相关文章:

python - 如何从两个范围中获取一个随机 float (python)

python - 为什么我不能在 Pandas 系列生成的绘图上设置 y 轴范围?

python - 多个 if 和 else 语句

python - matplotlib 中带有图例和随机点顺序的散点图

python - matplotlib子图的怪异之处

python - 用 Pandas 调整子图布局

colors - Scilab 图背景颜色

python - 列表列表的排列

python - 我可以从 numpy 数组列表中创建一个具有一个可变维度的 numpy 数组吗?

python - tempfile 和 listdir 奇怪的行为