def draw_legend(data, obj):
    """Adds legend code.
    """
    texts = []
    children_alignment = []
    for text in obj.texts:
        texts.append("{}".format(text.get_text()))
        children_alignment.append("{}".format(text.get_horizontalalignment()))

    # Get the location.
    # http://matplotlib.org/api/legend_api.html
    loc = obj._loc if obj._loc != 0 else _get_location_from_best(obj)
    pad = 0.03
    position, anchor = {
        1: (None, None),  # upper right
        2: ([pad, 1.0 - pad], "north west"),  # upper left
        3: ([pad, pad], "south west"),  # lower left
        4: ([1.0 - pad, pad], "south east"),  # lower right
        5: ([1.0 - pad, 0.5], "east"),  # right
        6: ([3 * pad, 0.5], "west"),  # center left
        7: ([1.0 - 3 * pad, 0.5], "east"),  # center right
        8: ([0.5, 3 * pad], "south"),  # lower center
        9: ([0.5, 1.0 - 3 * pad], "north"),  # upper center
        10: ([0.5, 0.5], "center"),  # center
    }[loc]

    # In case of given position via bbox_to_anchor parameter the center
    # of legend is changed as follows:
    if obj._bbox_to_anchor:
        bbox_center = obj.get_bbox_to_anchor()._bbox._points[1]
        position = [bbox_center[0], bbox_center[1]]

    legend_style = []
    if position:
        ff = data["float format"]
        legend_style.append(
            ("at={{(" + ff + "," + ff + ")}}").format(position[0], position[1])
        )
    if anchor:
        legend_style.append("anchor={}".format(anchor))

    # Get the edgecolor of the box
    if obj.get_frame_on():
        edgecolor = obj.get_frame().get_edgecolor()
        data, frame_xcolor, _ = mycol.mpl_color2xcolor(data, edgecolor)
        if frame_xcolor != "black":  # black is default
            legend_style.append("draw={}".format(frame_xcolor))
    else:
        legend_style.append("draw=none")

    # Get the facecolor of the box
    facecolor = obj.get_frame().get_facecolor()
    data, fill_xcolor, _ = mycol.mpl_color2xcolor(data, facecolor)
    if fill_xcolor != "white":  # white is default
        legend_style.append("fill={}".format(fill_xcolor))

    # Get the horizontal alignment
    try:
        alignment = children_alignment[0]
    except IndexError:
        alignment = None

    for child_alignment in children_alignment:
        if alignment != child_alignment:
            warnings.warn("Varying horizontal alignments in the legend. Using default.")
            alignment = None
            break

    if alignment:
        data["current axes"].axis_options.append(
            "legend cell align={{{}}}".format(alignment)
        )

    if obj._ncol != 1:
        data["current axes"].axis_options.append("legend columns={}".format(obj._ncol))

    # Write styles to data
    if legend_style:
        style = "legend style={{{}}}".format(", ".join(legend_style))
        data["current axes"].axis_options.append(style)

    return data
Adds legend code.