How do I set the background box size of legends in matplotlib?
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.
Is there any way to achieve that?
Code to reproduce the shown example:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
loc = "center left"
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"$\tan(x) = \frac{\sin(x)}{\cos(x)}$")
ax.plot(x, np.tan(2*x), label=r"$\tan(2x)$")
ax.plot(x, np.tan(3*x), label=r"$\tan(3x)$")
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"$\sin(x)$")
ax.plot(x, np.sin(2*x), label=r"$\sin(2x)$")
ax.plot(x, np.sin(4*x), label=r"$\sin(4x)$")
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"$\sin(x) \times \cos(x)$")
ax.plot(x, np.sin(2*x) * np.cos(2*x), label=r"$\sin(2x) \times \cos(2x)$")
ax.plot(x, np.sin(3*x) * np.cos(3*x), label=r"$\sin(3x) \times \cos(3x)$")
ax.legend(loc=loc, bbox_to_anchor=(1.02, 0.5))
plt.show()