title: Aligning legends to the right in matplotlib
body: <p>I am trying to align legends on my figure to the right. Here is the section of the script that performs the alignment. It works when I save the image as .png or .jpeg, but fails for .pdf and .eps. Any solution/suggestion would be warmly welcomed. Thanks in advance.</p>
  <pre><code># Shrink current axis by 20%
  box = ax1.get_position()
  ax1.set_position([box.x0, box.y0, box.width * 0.8, box.height])
      
  leg=ax1.legend(loc='center left', fontsize=tsize, ncol=1, frameon=False, fancybox=False, facecolor=None, edgecolor=None, framealpha=None, bbox_to_anchor=(1, 0.5))
  # get the width of your widest label, since every label will need 
  # to shift by this amount after we align to the right
  renderer = fig.canvas.get_renderer()
  shift = max([t.get_window_extent(renderer).width for t in leg.get_texts()])
  for t in leg.get_texts():
      t.set_ha('right') # ha is alias for horizontalalignment
      tmp_shift = abs(shift - t.get_window_extent(renderer).width)
      t.set_position((tmp_shift-50,0))
      
  fnam = path+'figure.'+fmt
  plt.savefig(fnam,format=fmt,dpi=DPI,bbox_inches=&quot;tight&quot;,pad_inches=0.05)
  print('Written file', fnam)
  </code></pre>
  <p>Here is a minimal script to produce the plot.</p>
  <pre><code>#------------------------------------------------------------------------------
  import matplotlib.pyplot as plt
  from matplotlib import rc
  rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})
  rc('text', usetex=True)
  # create figure suitable for A4 format
  def mm2inch(*tupl):
   inch = 25.4
   if isinstance(tupl[0], tuple):
    return tuple(i/inch for i in tupl[0])
   else:
     return tuple(i/inch for i in tupl)
  
  #------------------------------------------------------------------------------
  fig = plt.figure(num=None, figsize=mm2inch(200.0, 150.0), dpi=200)
  
  ax1 = plt.subplot2grid((1, 1), (0, 0), rowspan=1, colspan=1)
  
  for axis in ['top','bottom','left','right']:
    ax1.spines[axis].set_linewidth(1)
  
  ax1.set_ylabel(r&quot;$y$&quot;,fontsize=20)
  ax1.set_xlabel(r&quot;$x$&quot;,fontsize=20)
  
  ax1.axvline(-10,ls='', marker='o', markersize=8, markeredgewidth=2, markeredgecolor='black', markerfacecolor='white', label=r'$\overline{P_{uu}}$')
  ax1.axvline(-10,ls='', marker='s', markersize=8, markeredgewidth=2, markeredgecolor='black', markerfacecolor='white', label=r'$-\overline{T_{uu}}$')
  ax1.axvline(-10,ls='', marker='^', markersize=8, markeredgewidth=2, markeredgecolor='black', markerfacecolor='white', label=r'$\overline{\Pi_{uu}}$')
  ax1.axvline(-10,ls='', marker='d', markersize=8, markeredgewidth=2, markeredgecolor='black', markerfacecolor='white', label=r'$\overline{D_{uu}}$')
  ax1.axvline(-10,ls='', marker='x', markersize=8, markeredgewidth=2, markeredgecolor='black', markerfacecolor='white', label=r'$-\overline{\epsilon_{uu}}$')
  
  ax1.set_xlim(0,25)
  ax1.set_ylim(-0.25,0.5)
  ax1.tick_params(axis='x', labelsize=10)
  ax1.tick_params(axis='y', labelsize=10)
  ax1.tick_params(which='both',bottom=True, top=True, left=True, right=True)
  ax1.tick_params(which='both',labelbottom=True, labeltop=False, labelleft=True, labelright=False)
  ax1.tick_params(which='both', width=1)
  ax1.tick_params(which='major',length=15)
  
  #-------------Part of the code which performs shrinking and alignment----------
  # Shrink current axis by 20%
  box = ax1.get_position()
  ax1.set_position([box.x0, box.y0, box.width * 0.8, box.height])
  
  leg=ax1.legend(loc='center left', fontsize=17, ncol=1, frameon=False, fancybox=False, facecolor=None, edgecolor=None, framealpha=None, bbox_to_anchor=(1, 0.5))
  renderer = fig.canvas.get_renderer()
  shift = max([t.get_window_extent(renderer).width for t in leg.get_texts()])
  for t in leg.get_texts():
      t.set_ha('right') # ha is alias for horizontalalignment
      tmp_shift = abs(shift - t.get_window_extent(renderer).width)
      t.set_position((tmp_shift-50,0))
  #------------------------------------------------------------------------------
  
  fmt='pdf'
  fnam = 'figure.'+fmt
  plt.savefig(fnam,format=fmt,dpi=200,bbox_inches=&quot;tight&quot;,pad_inches=0.05)
  print('Written file', fnam)
  </code></pre>
  <p>It works for png and jpeg, but fails for pdf.</p>
  <p><a href="https://i.stack.imgur.com/4LUv4.png" rel="nofollow noreferrer">png image</a>
  <a href="https://i.stack.imgur.com/IGocO.png" rel="nofollow noreferrer">pdf image</a></p>