import io
import base64


def get_image_html_tag(fig, format="svg"):
    """
    Returns an HTML tag with embedded image data in the given format.

    :param fig: a matplotlib figure instance
    :param format: output image format (passed to fig.savefig)
    """
    stream = io.BytesIO()
    # bbox_inches: expand the canvas to include the legend that was put outside the plot
    # see https://stackoverflow.com/a/43439132
    fig.savefig(stream, format=format, bbox_inches="tight")
    data = stream.getvalue()

    if format == "svg":
        return data.decode("utf-8")
    data = base64.b64encode(data).decode("utf-8")
    return f"<img src=\"data:image/{format};base64,{data}\">"