我在使用Matplotlib绘图库时遇到了一个问题,就是当我直接使用gridspec或subplot2grid指定绘图位置时,我无法访问现有的子图。如果使用常规的subplot规范,例如add_subplot(211),则会返回任何现有的轴。但是,使用gridspec/subplot2grid似乎会破坏任何现有的轴。我该如何使用gridspec/subplot2grid检索现有的轴对象?这是预期的行为还是我漏掉了什么?我希望找到一种解决方案,不必为轴对象定义占位符。
示例:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
x = np.linspace(0,10,100)
y1 = np.cos(x)
y2 = np.sin(x)
fig = plt.figure()
ax = fig.add_subplot(211)
ax.plot(x,y1, '-b')
ax = fig.add_subplot(212)
ax.plot(x,y2, '-b')
ax = fig.add_subplot(211) #here, the existing axes object is retrieved
ax.plot(x,y2, '-r')
fig = plt.figure()
gs = gridspec.GridSpec(2,1)
ax = fig.add_subplot(gs[0,0])
ax.plot(x,y1, '-b')
ax = fig.add_subplot(gs[1,0])
ax.plot(x,y2, '-b')
# using gridspec (or subplot2grid), existing axes
# object is apparently deleted
ax = fig.add_subplot(gs[0,0])
ax.plot(x,y2, '-r')
plt.show()