2013-07-11 84 views
2

我有两个文件的数据:datafile1和datafile2,第一个始终存在,第二个只有时。所以datafile2上的数据图在我的python脚本中定义为一个函数(geom_macro)。在datafile1上的数据绘图代码的末尾,我首先测试datafile2是否存在,如果是,我调用已定义的函数。但我在案件中得到的是两个单独的数字,而不是一个与第二个的信息在另一个之上。 我的剧本的那部分看起来是这样的:如何在matplotlib中的另一个绘图上添加绘图?

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

呼叫

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

你不使axgeom_macro参数 - 如果ax是在全局命名空间,这将是从geom_macro中访问反正。不过,我认为明确陈述geom_macro使用ax更清晰,而且通过将其作为参数,可以使geom_macro更具可重用性 - 也许在某些时候,您希望使用多个子区块,然后它将会有必要指定您希望geom_macro绘制哪个轴。

+0

非常感谢,它的工作非常完美!并感谢对geom_macro明确声明使用ax的优势的额外评论。谢谢! – jealopez