Wednesday, April 1, 2009

Inset axes

A little script to have your inset axes to adjust its position relative to the parent axes. The inset position is calculated in the drawing time, thus it works even if the parent axes change its position (e.g., aspect=1).

import matplotlib.transforms

class InsetPosition(object):
def __init__(self, parent, lbwh):
self.parent = parent
self.lbwh = lbwh # position of the inset axes in the
normalized coordinate of the parent axes

def __call__(self, ax, renderer):
bbox_parent = self.parent.get_position(original=False)
trans = matplotlib.transforms.BboxTransformTo(bbox_parent)
bbox_inset = matplotlib.transforms.Bbox.from_bounds(*self.lbwh)
bb = matplotlib.transforms.TransformedBbox(bbox_inset, trans)
return bb

ax = gca()
axins = axes([0, 0, 1, 1])
ip = InsetPosition(ax, [0.5, 0.1, 0.4, 0.2])

  • anchor to the parent axes
  • adjust the inset size according to its data limits