我想创建一个带有两个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