title: Creating figure with exact size and no padding (and legend outside the axes)
body: <p>I am trying to make some figures for a scientific article, so I want my figures to have a specific size. I also see that Matplotlib by default adds a lot of padding on the border of the figures, which I don't need (since the figures will be on a white background anyway).</p>
  
  <p>To set a specific figure size I simply use <code>plt.figure(figsize = [w, h])</code>, and I add the argument <code>tight_layout = {'pad': 0}</code> to remove the padding. This works perfectly, and even works if I add a title, y/x-labels etc. Example:</p>
  
  <pre><code>fig = plt.figure(
      figsize = [3,2],
      tight_layout = {'pad': 0}
  )
  ax = fig.add_subplot(111)
  plt.title('title')
  ax.set_ylabel('y label')
  ax.set_xlabel('x label')
  plt.savefig('figure01.pdf')
  </code></pre>
  
  <p>This creates a pdf file with exact size 3x2 (inches).</p>
  
  <p><a href="https://i.stack.imgur.com/rA2d5.png" rel="noreferrer"><img src="https://i.stack.imgur.com/rA2d5.png" alt="figure01.png"></a></p>
  
  <p>The issue I have is that when I for example add a text box outside the axis (typically a legend box), Matplotlib does not make room for the text box like it does when adding titles/axis labels. Typically the text box is cut off, or does not show in the saved figure at all. Example:</p>
  
  <pre><code>plt.close('all')
  fig = plt.figure(
      figsize = [3,2],
      tight_layout = {'pad': 0}
  )
  ax = fig.add_subplot(111)
  plt.title('title')
  ax.set_ylabel('y label')
  ax.set_xlabel('x label')
  t = ax.text(0.7, 1.1, 'my text here', bbox = dict(boxstyle = 'round'))
  plt.savefig('figure02.pdf')
  </code></pre>
  
  <p><a href="https://i.stack.imgur.com/IiwkM.png" rel="noreferrer"><img src="https://i.stack.imgur.com/IiwkM.png" alt="figure02.png"></a></p>
  
  <p>A solution I found elsewhere on SO was to add the argument <code>bbox_inches = 'tight'</code> to the savefig command. The text box is now included like I wanted, but the pdf is now the wrong size. It seems like Matplotlib just makes the figure bigger, instead of reducing the size of the axes like it does when adding titles and x/y-labels.</p>
  
  <p>Example:</p>
  
  <pre><code>plt.close('all')
  fig = plt.figure(
      figsize = [3,2],
      tight_layout = {'pad': 0}
  )
  ax = fig.add_subplot(111)
  plt.title('title')
  ax.set_ylabel('y label')
  ax.set_xlabel('x label')
  t = ax.text(0.7, 1.1, 'my text here', bbox = dict(boxstyle = 'round'))
  plt.savefig('figure03.pdf', bbox_inches = 'tight')
  </code></pre>
  
  <p><a href="https://i.stack.imgur.com/5Es2Q.png" rel="noreferrer"><img src="https://i.stack.imgur.com/5Es2Q.png" alt="figure03.png"></a></p>
  
  <p>(This figure is 3.307x2.248)</p>
  
  <p>Is there any solution to this that covers most cases with a legend just outside the axes?</p>