Answer a question

I have a plotting function similar to this one

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)

When I define the function above in ipython (using the --pylab option), and then call

fct()
colorbar()

I get an error

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

Then it works. I guess this has to do with garbage collection - how can I prevent this problem in the first example?

Answers

It is because you first example, you are using ax.polormesh, not pyplot.polotmesh (namespace imported by pylab), when you call colorbar() (actually plt.colorbar()), it lost track of which mappable and which ax it should make colorbar to.

Therefore adding these lines will make it work:

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

Now you mentioned that your actual plot is a much more complex one. You want to make sure it is the ax.get_children()[2] or you can pick the it by look for a matplotlib.collections.QuadMesh instance.

Logo

学AI,认准AI Studio!GPU算力,限时免费领,邀请好友解锁更多惊喜福利 >>>

更多推荐