2

I'm trying to make a plot where the various subplots all share a colorbar similar to this answer. The problem that I'm running into is that in my script, I'm calling a function which creates the QuadMesh (generated from ax.pcolormesh) instance and returns the Figure and Axes instances associated with it. Is there any way to get a handle on the QuadMesh instance from the Axes instance (or Figure instance)?

import matplotlib.pyplot as plt
import numpy as np

def foo(subplot):
    data = np.random.random((100,100))
    x,y = np.meshgrid(np.arange(101),np.arange(101))
    fig = plt.gcf()
    ax = fig.add_subplot(subplot)
    quadmesh = ax.pcolormesh(x,y,data)
    return fig,ax

fig = plt.figure()
f,a = foo(221)
f,a = foo(222)
f,a = foo(223)
f,a = foo(224)
fig.subplots_adjust(right=0.8)
cbar_ax = fig.add_axes([0.85,0.15,0.05,0.7])
#fig.colorbar(magic_get_quadmesh,cax=cbar_ax)
plt.show()
Community
  • 1
  • 1
mgilson
  • 300,191
  • 65
  • 633
  • 696

1 Answers1

5

I'm not really sure this is what you want -- especially since there are 4 quadmeshes -- but you can find the quadmesh given the AxesSubplot via its collections attribute:

fig.colorbar(a.collections[0], cax=cbar_ax)

By the way, I found the answer using this exploratory introspection tool:

def describe(obj):
    for key in dir(obj):
        try:
            val = getattr(obj, key)
        except AttributeError:
            continue
        if callable(val):
            help(val)
        else:
            print('{k} => {v!r}'.format(k=key, v=val))
        print('-' * 80)
describe(a)

Yeah, it prints out a lot of output, but a quick search for "quadmesh" leads you to the answer.

unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
  • That's exactly what I want. Since all of the quadmeshes need to share the same colorbar, they're all actually created with the same arguments passed to `quadmesh.set_clim`. So, as long as I have a handle on one of the quadmesh objects, I can create the colorbar I want. Will accept in 5 min or so :) – mgilson May 24 '13 at 17:48
  • Oh nice. I looked through the output of `dir`, but didn't find anything off the bat ... so I thought I'd post a question here. (maybe it'll help someone else someday) – mgilson May 24 '13 at 17:51