4

I want to add a colorbar WITHOUT what is returned by the axis on plotting things. Sometimes I draw things to an axis inside a function, which returns nothing. Is there a way to get the mappable for a colorbar from an axis where a plotting has been done beforehand? I believe there is enough information about colormap and color range bound to the axis itself.

I'd like tp do something like this:

def plot_something(ax):
    ax.plot( np.random.random(10), np.random.random(10), c= np.random.random(10))

fig, axs = plt.subplots(2)
plot_something(axs[0])
plot_something(axs[1])

mappable = axs[0].get_mappable() # a hypothetical method I want to have.

fig.colorbar(mappable)
plt.show()

EDIT

The answer to the possible duplicate can partly solve my problem as is given in the code snippet. However, this question is more about retrieving a general mappable object from an axis, which seems to be impossible according to Diziet Asahi.

Hoseung Choi
  • 1,017
  • 2
  • 12
  • 20
  • Possible duplicate of [Matplotlib - add colorbar to a sequence of line plots](https://stackoverflow.com/questions/8342549/matplotlib-add-colorbar-to-a-sequence-of-line-plots) – DavidG Jan 07 '18 at 10:38

1 Answers1

5

The way you could get your mappable would depend on what plotting function your are using in your plot_something() function.

for example:

  • plot() returns a Line2D object. A reference to that object is stored in the list ax.lines of the Axes object. That being said, I don't think a Line2D can be used as a mappable for colorbar()
  • scatter() returns a PathCollection collection object. This object is stored in the ax.collections list of the Axes object.
  • On the other hand, imshow() returns an AxesImage object, which is stored in ax.images

You might have to try and look in those different list until you find an appropriate object to use.

def plot_something(ax):
    x = np.random.random(size=(10,))
    y = np.random.random(size=(10,))
    c = np.random.random(size=(10,))
    ax.scatter(x,y,c=c)

fig, ax = plt.subplots()
plot_something(ax)
mappable = ax.collections[0]
fig.colorbar(mappable=mappable)
Diziet Asahi
  • 38,379
  • 7
  • 60
  • 75
  • 1
    Hmm... after all, there is no unified way to refer to the mappable object. Then I think this is not a good direction to take. I should try to avoid making plots in this way. – Hoseung Choi Jan 15 '18 at 05:09