2013-07-11 85 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