我想创建一个有两个y轴的图形,并在我的代码中的不同点(来自不同的函数)为每个轴添加多条曲线。
在第一个函数中,我创建了一个图形:
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(),而不是返回现有的一个句柄。
如何正确地获取曲线图中已经存在的双轴的句柄?
发布于 2017-03-08 23:20:45
我猜最干净的方法是在函数外部创建轴。然后,您可以为函数提供您喜欢的任何轴。
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()发布于 2019-11-01 02:36:26
可以使用get_shared_x_axes (get_shared_y_axes)获取由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 Truehttps://stackoverflow.com/questions/42674563
复制相似问题