# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

# %matplotlib inline
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib as mpl
import matplotlib.patches as mpatches

mpl.get_backend()

mpl.use('MacOSX')


# +
def get_location_of_legend_box(leg_artist):
    frame = leg_artist.get_frame()
    x0 = frame.get_x()
    y0 = frame.get_y()
    x1 = x0 + frame.get_width()
    y1 = y0 + frame.get_height()
    ax_box_coord = ax.transAxes.inverted().transform([[x0, y0], [x1, y1]])
    width = ax_box_coord[1, 0] - ax_box_coord[0, 0]
    height = ax_box_coord[1, 1] - ax_box_coord[0, 1]
    lowest_point = ax_box_coord[0, 1]
    farthest_point = ax_box_coord[1, 0]
    return width,height,lowest_point,farthest_point

def arrange_legend_boxs(legs_hl_list,ax):
    current_lowest_point = 1
    current_farthest_point = 1
    last_farthest_point = None
    have_legend_in_the_column = False
    ready_legend_artist = []
    for item in legs_hl_list:
        leg_artist = ax.legend(handles=item[0],labels=item[1],loc='upper left',bbox_to_anchor=(current_farthest_point,current_lowest_point))
        plt.pause(0.01)
        width,height,lowest_point,farthest_point = get_location_of_legend_box(leg_artist)
        if have_legend_in_the_column:
            if lowest_point < 0:
                current_farthest_point = max([last_farthest_point,farthest_point])
                leg_artist = ax.legend(handles=item[0],labels=item[1],loc='upper left',bbox_to_anchor=(current_farthest_point,1))
                plt.pause(0.01)
                width, height, lowest_point, farthest_point = get_location_of_legend_box(leg_artist)
        current_lowest_point = lowest_point
        last_farthest_point = farthest_point
        ready_legend_artist.append(leg_artist)
        have_legend_in_the_column = True

    for artist in ready_legend_artist:
        ax.add_artist(artist)


# -

## test
leg1_hl = ([mpatches.Patch(color=i) for i in 'rgb'], ['r', 'g', 'b'])
leg2_hl = ([mpatches.Patch(color=i) for i in 'rgb'], ['r', 'g', 'b'])
leg3_hl = ([mpatches.Patch(color=i) for i in 'rgb'], ['r', 'g', 'b'])
leg4_hl = ([mpatches.Patch(color=i) for i in 'rgb'], ['r', 'g', 'b'])
leg5_hl = ([mpatches.Patch(color=i) for i in 'rgb'], ['r', 'g', 'b'])
leg6_hl = ([mpatches.Patch(color=i) for i in 'rgb'], ['r', 'g', 'b'])
fig,ax = plt.subplots()
arrange_legend_boxs([leg1_hl,leg2_hl,leg3_hl,leg4_hl,leg5_hl,leg6_hl],ax)





StarcoderdataJupyterScriptsDedupFiltered