def optimally_align_text(x, y, texts, expand=(<NUM_LIT:1.>, <NUM_LIT:1.>), add_bboxes=[],<EOL>renderer=None, ax=None,<EOL>direction='<STR_LIT>'):
if ax is None:<EOL><INDENT>ax = plt.gca()<EOL><DEDENT>if renderer is None:<EOL><INDENT>r = get_renderer(ax.get_figure())<EOL><DEDENT>else:<EOL><INDENT>r = renderer<EOL><DEDENT>xmin, xmax = sorted(ax.get_xlim())<EOL>ymin, ymax = sorted(ax.get_ylim())<EOL>bboxes = get_bboxes(texts, r, expand, ax=ax)<EOL>if '<STR_LIT:x>' not in direction:<EOL><INDENT>ha = ['<STR_LIT>']<EOL><DEDENT>else:<EOL><INDENT>ha = ['<STR_LIT:left>', '<STR_LIT:right>', '<STR_LIT>']<EOL><DEDENT>if '<STR_LIT:y>' not in direction:<EOL><INDENT>va = ['<STR_LIT>']<EOL><DEDENT>else:<EOL><INDENT>va = ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>']<EOL><DEDENT>alignment = list(product(ha, va))<EOL><INDENT>coords = np.array(zip(x, y))<EOL><DEDENT>for i, text in enumerate(texts):<EOL><INDENT>tcoords = np.array(text.get_position()).T<EOL>nonself_coords = coords[~np.all(coords==tcoords, axis=<NUM_LIT:1>)]<EOL>nonself_x, nonself_y = np.split(nonself_coords, <NUM_LIT:2>, axis=<NUM_LIT:1>)<EOL>
For all text objects find alignment that causes the least overlap with
points and other texts and apply it