2017-03-08 94 views
2

我想創建一個帶有兩個y軸的圖形,並在我的代碼中的不同點(從不同的函數)向這些軸中的每個軸添加多條曲線。matplotlib:如何獲取現有twinx()軸的句柄?

在第一個功能,我創建了一個數字:

import matplotlib.pyplot as plt 
    from numpy import * 

    # Opens new figure with two axes 
    def function1(): 
      f = plt.figure(1) 
      ax1 = plt.subplot(211) 
      ax2 = ax1.twinx() 

      x = linspace(0,2*pi,100) 
      ax1.plot(x,sin(x),'b') 
      ax2.plot(x,1000*cos(x),'g') 

    # other stuff will be shown in subplot 212... 

現在,在第二個功能我想要的曲線添加到每個已創建軸:

def function2(): 
      # Get handles of figure, which is already open 
      f = plt.figure(1) 
      ax3 = plt.subplot(211).axes # get handle to 1st axis 
      ax4 = ax3.twinx()   # get handle to 2nd axis (wrong?) 

      # Add new curves 
      x = linspace(0,2*pi,100) 
      ax3.plot(x,sin(2*x),'m') 
      ax4.plot(x,1000*cos(2*x),'r') 

現在我的問題在於,在第二個代碼塊執行後(所有其他代碼塊),第一個代碼塊中添加的綠色曲線不再可見。

我想這樣做的原因是我的第二個代碼塊的行

ax4 = ax3.twinx() 

。它可能會創建一個新的twinx(),而不是返回現有句柄。

我該如何正確獲取已經存在的雙軸座標圖中的手柄?

+0

爲什麼不存儲在第一個函數中創建的座標軸並在第二個座標系中使用它們,而不是試圖從數字中重新驅動它們? – pingul

回答

0

我猜想最簡潔的方法是創建函數外的軸。然後你可以提供你喜歡的任何軸到函數。

import matplotlib.pyplot as plt 
import numpy as np 

def function1(ax1, ax2): 
    x = np.linspace(0,2*np.pi,100) 
    ax1.plot(x,np.sin(x),'b') 
    ax2.plot(x,1000*np.cos(x),'g') 

def function2(ax1, ax2): 
    x = np.linspace(0,2*np.pi,100) 
    ax1.plot(x,np.sin(2*x),'m') 
    ax2.plot(x,1000*np.cos(2*x),'r') 

fig, (ax, bx) = plt.subplots(nrows=2) 
axtwin = ax.twinx() 

function1(ax, axtwin) 
function2(ax, axtwin) 

plt.show() 
+0

謝謝,你說得對,這是更清潔的解決方案。 – rmnboss