code: def optimally_align_text(
      x,
      y,
      texts,
      expand=(1.0, 1.0),
      add_bboxes=[],
      renderer=None,
      ax=None,
      direction="xy",
  ):
      """
      For all text objects find alignment that causes the least overlap with
      points and other texts and apply it
      """
      if ax is None:
          ax = plt.gca()
      if renderer is None:
          r = get_renderer(ax.get_figure())
      else:
          r = renderer
      xmin, xmax = sorted(ax.get_xlim())
      ymin, ymax = sorted(ax.get_ylim())
      bboxes = get_bboxes(texts, r, expand, ax=ax)
      if "x" not in direction:
          ha = [""]
      else:
          ha = ["left", "right", "center"]
      if "y" not in direction:
          va = [""]
      else:
          va = ["bottom", "top", "center"]
      alignment = list(product(ha, va))
      #    coords = np.array(zip(x, y))
      for i, text in enumerate(texts):
          #        tcoords = np.array(text.get_position()).T
          #        nonself_coords = coords[~np.all(coords==tcoords, axis=1)]
          #        nonself_x, nonself_y = np.split(nonself_coords, 2, axis=1)
          counts = []
          for h, v in alignment:
              if h:
                  text.set_ha(h)
              if v:
                  text.set_va(v)
              bbox = (
                  text.get_window_extent(r)
                  .expanded(*expand)
                  .transformed(ax.transData.inverted())
              )
              c = len(get_points_inside_bbox(x, y, bbox))
              intersections = [
                  bbox.intersection(bbox, bbox2) if i != j else None
                  for j, bbox2 in enumerate(bboxes + add_bboxes)
              ]
              intersections = sum(
                  [
                      abs(b.width * b.height) if b is not None else 0
                      for b in intersections
                  ]
              )
              # Check for out-of-axes position
              bbox = text.get_window_extent(r).transformed(
                  ax.transData.inverted()
              )
              x1, y1, x2, y2 = (
                  bbox.xmin,
                  bbox.ymin,
                  bbox.xmax,
                  bbox.ymax,
              )
              if x1 < xmin or x2 > xmax or y1 < ymin or y2 > ymax:
                  axout = 1
              else:
                  axout = 0
              counts.append((axout, c, intersections))
          # Most important: prefer alignments that keep the text inside the axes.
          # If tied, take the alignments that minimize the number of x, y points
          # contained inside the text.
          # Break any remaining ties by minimizing the total
          # area of intersections
          # with all text bboxes and other objects to avoid.
          a, value = min(enumerate(counts), key=itemgetter(1))
          if "x" in direction:
              text.set_ha(alignment[a][0])
          if "y" in direction:
              text.set_va(alignment[a][1])
          bboxes[i] = (
              text.get_window_extent(r)
              .expanded(*expand)
              .transformed(ax.transData.inverted())
          )
      return texts
  
imports: from __future__ import division
  import sys
  from itertools import product
  from operator import itemgetter
  import matplotlib
  import numpy
  from matplotlib import pyplot
  from matplotlib.path import get_path_collection_extents
label_desc: Use image node_id 9 for calling a global function with example usage: optimally_align_text(x, y, texts, expand, add_bboxes, renderer, ax, direction) and returns: texts