我想創建一個帶有兩個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(),而不是返回現有句柄。
我該如何正確獲取已經存在的雙軸座標圖中的手柄?
爲什麼不存儲在第一個函數中創建的座標軸並在第二個座標系中使用它們,而不是試圖從數字中重新驅動它們? – pingul