matplotlib colorbar不工作(由于垃圾收集?)

2024-09-28 18:54:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个类似的绘图功能

def fct():
    f=figure()
    ax=f.add_subplot(111)
    x,y=mgrid[0:5,0:5]
    z=sin(x**2+y**2)
    ax.pcolormesh(x,y,z)

当我在ipython(使用--pylab选项)中定义上述函数时,然后调用

fct()
colorbar()

我有个错误

"RuntimeError: No mappable was found to use for colorbar creation.".

def fct():
    f=figure()
    x,y=mgrid[0:5,0:5]
    z=sin(x**2+y**2)
    pcolormesh(x,y,z)

那就行了。我想这与垃圾收集有关—在第一个示例中,如何防止出现此问题?


Tags: 功能add绘图def选项ipythonsinax
4条回答

这是因为您的第一个例子,您使用的是ax.polormesh,而不是pyplot.polotmesh(由pylab导入的名称空间),当您调用colorbar()(实际上是plt.colorbar())时,它失去了跟踪哪个可映射的以及它应该使colorbar指向哪个ax的信息。

因此,添加这些行将使其工作:

import matplotlib.pyplot as plt
fct()
ax=plt.gca() #get the current axes
PCM=ax.get_children()[2] #get the mappable, the 1st and the 2nd are the x and y axes
plt.colorbar(PCM, ax=ax) 

enter image description here

现在你提到你的真实情节要复杂得多。您需要确保它是ax.get_children()[2],或者可以通过查找matplotlib.collections.QuadMesh实例来选择它。

我认为这与pylab状态机和作用域有关。

一个更好的做法是这样做(显式比隐式好):

import numpy as np
import matplotlib.pyplot as plt

def fct():
    f = plt.figure()
    ax = f.add_subplot(111)
    x, y = np.mgrid[0:5,0:5]
    z = np.sin(x**2+y**2)
    mesh = ax.pcolormesh(x, y ,z)

    return ax, mesh

ax, mesh = fct()
plt.colorbar(mesh, ax=ax)

您的函数很小,不需要参数,所以您真的需要将绘图包装在函数中吗?怎么办:

import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots(1, 1)
x, y = np.mgrid[0:5,0:5]
z = np.sin(x**2+y**2)
mesh = ax.pcolormesh(x, y ,z)
fig.colorbar(mesh)
plt.show()

enter image description here

这是因为您的第一个例子,您使用的是ax.polormesh,而不是pyplot.polotmesh(由pylab导入的名称空间),当您调用colorbar()(实际上是plt.colorbar())时,它丢失了哪个可映射的以及它应该将colorbar设置为哪个ax的跟踪。

因此,添加这些行将使其工作:

import matplotlib.pyplot as plt
fct()
ax=plt.gca() #get the current axes
PCM=ax.get_children()[2] #get the mappable, the 1st and the 2nd are the x and y axes
plt.colorbar(PCM, ax=ax) 

enter image description here

现在你提到你的真实情节要复杂得多。您需要确保它是ax.get_children()[2],或者可以通过查找matplotlib.collections.QuadMesh实例来选择它。

相关问题 更多 >