如何在 matplotlib 中的另一个图上添加一个图?

jea*_*pez 4 python matplotlib user-defined-functions

我有两个包含数据的文件:datafile1 和 datafile2,第一个始终存在,第二个仅有时存在。因此,datafile2 上的数据图被定义为我的 python 脚本中的函数 (geom_macro)。在 datafile1 上的数据绘制代码结束时,我首先测试 datafile2 是否存在,如果存在,则调用定义的函数。但我在这个案例中得到的是两个独立的数字,而不是一个将第二个数字的信息叠加在另一个数字之上的信息。我的脚本的这一部分如下所示:

f = plt.figuire()
<in this section a contour plot is defined of datafile1 data, axes, colorbars, etc...>

if os.path.isfile('datafile2'):
    geom_macro()

plt.show()
Run Code Online (Sandbox Code Playgroud)

“geom_macro”函数如下所示:

def geom_macro():
    <Data is collected from datafile2 and analyzed>
    f = plt.figure()
    ax = f.add_subplot(111)
    <annotations, arrows, and some other things are defined>
Run Code Online (Sandbox Code Playgroud)

有没有一种类似于“append”语句用于在列表中添加元素的方法,可以在 matplotlib pyplot 中使用它来将绘图添加到现有绘图中?感谢您的帮助!

unu*_*tbu 5

称呼

fig, ax = plt.subplots()
Run Code Online (Sandbox Code Playgroud)

一次。要将多个图添加到同一轴,请调用ax的方法:

ax.contour(...)
ax.plot(...)
# etc.
Run Code Online (Sandbox Code Playgroud)

不要拨打f = plt.figure()两次。


def geom_macro(ax):
    <Data is collected from datafile2 and analyzed>
    <annotations, arrows, and some other things are defined>
    ax.annotate(...)

fig, ax = plt.subplots()
<in this section a contour plot is defined of datafile1 data, axes, colorbars, etc...>

if os.path.isfile('datafile2'):
    geom_macro(ax)

plt.show()
Run Code Online (Sandbox Code Playgroud)

您不必争论--如果位于全局名称空间中,ax则无论如何都可以从内部访问它。然而,我认为明确声明使用 更清晰,而且,通过将其作为一个参数,您可以使其更可重用——也许在某些时候您会想要使用多个子图,然后有必要指定您要在哪个轴上绘制。geom_macroaxgeom_macrogeom_macroaxgeom_macrogeom_macro