如何使用Matplotlib中的subplot2grid/gridspec检索现有子地块轴?

如何使用Matplotlib中的subplot2grid/gridspec检索现有子地块轴?,matplotlib,Matplotlib,当直接使用gridspec或subplot2grid指定绘图位置时,访问Matplotlib图形中的现有子绘图时遇到问题。常规子地块规格,例如添加子地块(211),返回现有轴(如果有)。使用gridspec/subplot2grid似乎会破坏任何现有轴。如何使用gridspec/subplot2grid检索现有的轴对象?这是故意的行为还是我在这里遗漏了什么?我想要一个解决方案,不必为轴对象定义自己的占位符 例如: import numpy as np import matplotlib.pypl

当直接使用gridspec或subplot2grid指定绘图位置时,访问Matplotlib图形中的现有子绘图时遇到问题。常规子地块规格,例如添加子地块(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()

这实际上是一个微妙的bug,它的神奇之处在于
add_subplot
如何确定轴是否存在。归结起来就是这样一个事实:

In [220]: gs[0, 0] == gs[0, 0]
Out[220]: False
这是因为
gridspec.\uuuuu getitem\uuuuuuuuu
每次调用时都会返回一个新对象,
SubplotSpec
不会重载
\uuuuuuu eq\uuuuu
所以python在搜索现有轴时会检查“内存中的对象是否相同”

这就是问题所在,但是我天真的尝试通过在
子PlotSpec
中添加
\uuuueq\uuuuu
和monkey patching
matplotlib.gridspec.SubplotSpec
来修复它,但如果您添加

def __eq__(self, other):
    return all((self._gridspec == other._gridspec,
                self.num1 == other.num1,
                self.num2 == other.num2))
类SubplotSpec(对象):
matplotlib/gridspec.py
~L380中,并按预期从源代码重新安装


这似乎打破了所有其他事情。

最简单的方法就是保留对它们的引用。是的,很容易做到,我想到目前为止我还是坚持这个解决方案。尽管如此,在我看来,对于指定子地块格式的各种方法,仍然需要一个统一的add_plot等行为。这是在github上发表该观点的最佳地方;)感谢您的澄清和纠正问题的努力。