【问题标题】:Adding figures to subplots in Matplotlib在 Matplotlib 中将图形添加到子图中
【发布时间】:2018-05-10 18:21:51
【问题描述】:

我是 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 手册,但到目前为止还没有运气。

【问题讨论】:

  • 我需要将图形广告添加到子情节中。我创建了两个图形,并希望将它们合并到一个图中。我试过你的方法,但它不起作用。谢谢。
  • 你的意思是this question?
  • 只是为了确保我们在同一行:您不能将一个图形添加到另一个图形或另一个图形内的任何内容。就像您不能在烤箱中添加烤箱一样。与其在两个烤箱中分别添加一个披萨,然后尝试将两个烤箱放入另一个烤箱,解决方案当然是将两个披萨放入同一个烤箱。
  • 我不明白那个回复。你可以拍两张照片,然后你有一张包含这两张照片的照片。我似乎是数字不能分层嵌套在 matplotlib 中,这是我们在这里需要的。这最终成为一个问题,例如在 seaborn 中使用 facetgrid 图时。据我所知,它们不能轻易地作为子图放置在更大的图中。

标签: python matplotlib


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2016-04-28
    • 2020-12-21
    • 1970-01-01
    • 2021-04-12
    • 1970-01-01
    • 2022-01-17
    • 2023-03-08
    • 2020-09-10
    • 2012-01-20
    相关资源
    最近更新 更多