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