def pad_limits(xgrid, ygrid, xpad=0.0, ypad=0.0, square=None):
    """
    Compute padded image limits for x and y grids.

    Parameters
    ----------
    xgrid : array
        Grid for x axis of image.
    ygrid : array
        Grid for y axis of image.
    xpad : float, optional
        Padding fraction for x axis (default: 0.).
    ypad : float, optional
        Padding fraction for y axis (default: 0.).
    square : axis object, optional
        Extend limits to have a square aspect ratio within an axis.

    """
    xmin, xmax = xgrid.min(), xgrid.max()
    ymin, ymax = ygrid.min(), ygrid.max()
    dx = xmax - xmin
    dy = ymax - ymin
    x0 = xmin - xpad * dx
    x1 = xmax + xpad * dx
    y0 = ymin - ypad * dy
    y1 = ymax + ypad * dy
    if square:
        axis = square
        ax_position = axis.get_position()
        ax_height = ax_position.height * axis.figure.get_figheight()
        ax_width = ax_position.width * axis.figure.get_figwidth()
        ax_aspect = ax_height / ax_width
        im_height = y1 - y0
        im_width = x1 - x0
        im_aspect = im_height / im_width
        if im_height / im_width > ax_height / ax_width:
            extra_w = im_height / ax_aspect - im_width
            x0 -= extra_w / 2
            x1 += extra_w / 2
        else:
            extra_h = im_width * ax_aspect - im_height
            y0 -= extra_h / 2
            y1 += extra_h / 2
    return [x0, x1, y0, y1]
