3

我有两个包含数据的文件: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()

“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>

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

4

1 回答 1

4

称呼

fig, ax = plt.subplots()

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

ax.contour(...)
ax.plot(...)
# etc.

不要调用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()

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

于 2013-07-11T21:21:42.343 回答