title: Python matplotlib set background rectangluar size of legend for grid spec
body: <p>How do I set the background box size of legends in matplotlib?</p>
  <hr />
  <p>Consider the left graph row alignment in pythons matplotlib (code posted in the end). The legends have been moved to the right because otherwise it covers essential data. They align vertically. But I feel like the different horizontal widths of the legends are kind of edgy. Therefore I want to change them to all have the same background box as shown in the right graph.</p>
  <p>Is there any way to achieve that?</p>
  <div class="s-table-container">
  <table class="s-table">
  <thead>
  <tr>
  <th style="text-align: center;">Current output</th>
  <th style="text-align: center;">Wanted  output</th>
  </tr>
  </thead>
  <tbody>
  <tr>
  <td style="text-align: center;"><a href="https://i.stack.imgur.com/7lphU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7lphU.png" alt="Row alignment of graphs" /></a></td>
  <td style="text-align: center;"><a href="https://i.stack.imgur.com/3Fp40.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3Fp40.png" alt="Desired alignment of the legends" /></a></td>
  </tr>
  </tbody>
  </table>
  </div><hr />
  <p>Code to reproduce the shown example:</p>
  <pre class="lang-py prettyprint-override"><code>import numpy as np
  import matplotlib.pyplot as plt
  from matplotlib.gridspec import GridSpec
  
  loc = &quot;center left&quot;
  x = np.linspace(-2 * np.pi, 2 * np.pi, 100)
  
  fig = plt.figure(figsize=(5, 5), constrained_layout=True)
  gs = GridSpec(3, 1, figure=fig)
  
  ax = fig.add_subplot(gs[0,:])
  ax.plot(x, np.tan(x), label=r&quot;$\tan(x) = \frac{\sin(x)}{\cos(x)}$&quot;)
  ax.plot(x, np.tan(2*x), label=r&quot;$\tan(2x)$&quot;)
  ax.plot(x, np.tan(3*x), label=r&quot;$\tan(3x)$&quot;)
  ax.legend(loc=loc, bbox_to_anchor=(1.02, 0.5))
  
  ax = fig.add_subplot(gs[1,:])
  ax.plot(x, np.sin(x), label=r&quot;$\sin(x)$&quot;)
  ax.plot(x, np.sin(2*x), label=r&quot;$\sin(2x)$&quot;)
  ax.plot(x, np.sin(4*x), label=r&quot;$\sin(4x)$&quot;)
  ax.legend(loc=loc, bbox_to_anchor=(1.02, 0.5))
  
  ax = fig.add_subplot(gs[2,:])
  ax.plot(x, np.sin(x) * np.cos(x), label=r&quot;$\sin(x) \times \cos(x)$&quot;)
  ax.plot(x, np.sin(2*x) * np.cos(2*x), label=r&quot;$\sin(2x) \times \cos(2x)$&quot;)
  ax.plot(x, np.sin(3*x) * np.cos(3*x), label=r&quot;$\sin(3x) \times \cos(3x)$&quot;)
  ax.legend(loc=loc, bbox_to_anchor=(1.02, 0.5))
  
  plt.show()
  </code></pre>