matplotlib 色条无法显示(由于垃圾回收?)

16 投票
4 回答
50609 浏览
提问于 2025-04-18 02:51

我有一个绘图函数,类似于下面这个

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: 没有找到可用于创建颜色条的映射对象。"

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

然后它就能正常工作了。我猜这跟垃圾回收有关——我该如何在第一个例子中防止这个问题呢?

4 个回答

2

对我来说,下面的代码没有奏效。

PCM=ax.get_children()[2] 
plt.colorbar(PCM, ax=ax)

因为我的图表稍微复杂一些,所以我根据@lib的评论,使用了以下代码。

ax=plt.gca() #get the current axes
for PCM in ax.get_children():
    if isinstance(PCM, mpl.cm.ScalarMappable):
        break
        
plt.colorbar(PCM, ax=ax)
5

你的这个函数很小,而且没有参数,那你真的有必要把绘图放在一个函数里吗?那这样做怎么样:

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()

在这里输入图片描述

9

我觉得这更多是跟 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)
20

这是因为在你的第一个例子中,你使用的是 ax.polormesh,而不是 pyplot.polotmesh(这个是通过 pylab 导入的命名空间)。当你调用 colorbar()(实际上是 plt.colorbar())时,它就不知道该给哪个图形和哪个坐标轴添加颜色条了。

所以,添加以下这些代码就能让它正常工作:

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 的实例来选择它。

撰写回答