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?
you can use get_shared_x_axes (get_shared_y_axes) to get a handle to the axes created by twinx (twiny):
# creat some axes
f,a = plt.subplots()
# create axes that share their x-axes
atwin = a.twinx()
# in case you don't have access to atwin anymore you can get a handle to it with
atwin_alt = a.get_shared_x_axes().get_siblings(a)[0]
atwin == atwin_alt # should be True
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With