def trans2fig(axis, rect, from_data=True):
    """Transform (data or axis) coordinates to figure coordinates.

    Inspired by: https://stackoverflow.com/a/17478227/38281.

    Usage:
    >>> rect = trans2fig(ax, [x,y,w,h])
    >>> ax2 = ax.figure.add_axes(rect)
    """
    x, y, w, h = rect

    FT = axis.figure.transFigure.inverted().transform

    if from_data:
        # Transform: data-->display-->figure
        T = lambda xy: FT(axis.transData.transform(xy))
    else:
        # Transform: axes-->display-->figure
        T = lambda xy: FT(axis.transAxes.transform(xy))

    x, y = T((x,y))
    w, h = T([w,h]) - T([0,0]) # affine transform wrt. 0

    return x,y,w,h