Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matplotlib colorbar not working (due to garbage collection?)

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?

like image 717
John Smith Avatar asked Apr 15 '14 17:04

John Smith


1 Answers

I think it has more to do with the pylab state machine and scoping.

A better practice would be to do the following (explicit is better than implicit):

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)
like image 144
Paul H Avatar answered Sep 17 '22 13:09

Paul H