在 Matplotlib 中将数字添加到子图中 [英] Adding figures to subplots in Matplotlib

查看:94
本文介绍了在 Matplotlib 中将数字添加到子图中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am new to matplotlib and am trying to get my head around how to add figures to a subplot.

我有三个不同的功能,可以输出一个数字:

I have three different functions, which output a single figure:

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轴的单个绘图.我试过了:

Now, for example I would like to merge both figures into a single plot with shared X axis. I tried:

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

and here I am basically lost. I'm reading the Matplotlib manual, but no luck so far.

推荐答案

除非您的函数签名必须保留在示例中定义的那样,否则在函数外部创建子图并传递适当的实例到每个功能.

Unless your function signatures have to stay as they are defined in your example it would be easier to create the subplots outside of the functions and pass the appropriate Axes instance to each function.

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])

如果您需要创建一个仅包含一个子图的图形,您可以这样做:

If you needed to create a figure containing just one of the subplots you can do so with:

fig, ax = plt.subplot()
plot_fig_1(..., ax)

或者,如果函数需要自包含,给 ax 参数一个默认值并在函数内部测试它.

Or, if the functions need to be self-contained, give the ax argument a default value and test for it inside the function.

def plot_fig_1(vars, args, ax=None):
    if ax is None:
        fig, ax = plt.subplot()
    # do something
    ax.plot(x, y)

这篇关于在 Matplotlib 中将数字添加到子图中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆