1

Figure.colorbar(mappable=...) has an argument to accept colorable items, such as AxesImage, ContourSet, etc. with this in mind, the usual usage is following:

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable


ax = plt.subplot()
im = ax.imshow(np.arange(100).reshape((10, 10)))

# create an axes on the right side of ax. The width of cax will be 5%
# of ax and the padding between cax and ax will be fixed at 0.05 inch.
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.05)

plt.colorbar(im, cax=cax)

enter image description here

In above example, the mappable im is returned by imshow(), which in most cases I think it's nice. My question is how can we return mappable directly from ax after we implemented ax.imshow() or ax.pcolormesh(), which should look like something below.

ax.imshow(np.arange(100).reshape((10, 10)))
def get_mappable(ax):
    pass

mappable = get_mappable(ax)

ax.images is not what I want, as this is only one type of mappables.

I looked back into some source code in plt.colorbar(), it uses gci()(here), but I tried and it returns None, I guess I must miss something important. Pls give me some direction, thank you very much.

Edits: I found an answer here, but it is very simialr to ax.images method.

Jiadong
  • 1,822
  • 1
  • 17
  • 37
  • One possible hurdle is that an `ax` can have multiple elements compatible with scalarmappable. Usually the reason to access that scalarmappable is to create a colorbar. What should the function to when there are multiple such elements? Return them all (it can be a huge list)? Or maybe try to find out whether or not they would lead to the same colorbar? Or ....? – JohanC Apr 05 '21 at 20:56
  • Hi, yes, but we can return current mappable . Similar concept in gcf(). It seems in source code, they use gci(), but I tried, it returned None... pls we can use gci(), I think it will be okay. Thanks for your reply. – Jiadong Apr 06 '21 at 00:04

0 Answers0