I want to create a figure with two y-axes and add multiple curves to each of those axes at different points in my code (from different functions).
In a first function, I create a figure:
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...
Now, in a second function I want to add a curve to each of the already created axes:
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')
Now my problem is that the green curve added in the first code block is not anymore visible after the second block is executed (all others are).
I think the reason for this is the line
ax4 = ax3.twinx()
in my second code block. It probably creates a new twinx() instead of returning a handle to the existing one.
How would I correctly get the handles to already existing twinx-axes in a plot?
I would guess that the cleanest way would be to create the axes outside the functions. Then you can supply whatever axes you like to the function.
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()