I am trying to show legends for each subplot in the figure that fit properly in the ax size (autoscaling fontsize, boxsize, etc.). I have tried many ways to fit legends but I have not found a non-intrincate manner. For example, in the answers to another posts (e.g. How to change legend size with matplotlib.pyplot) the user have to decide the legend size (fontsize and titlesize) but I am asking for a way to automatically fit the legend inside axes in a figure with multiple subplots.
I want the legend size to fit inside each ax in the Figure 1 created with the example code attached with ax.legend()
line commented. In Figure 2 I show the figure obtained with ax.legend()
line active : legends do not fit inside axes. Attached code is a modified version of the example in Matplotlib Examples : Creating multiple subplots using plt.subplots
import matplotlib.pyplot as plt
import numpy as np
# Some example data to display
x = np.linspace(0, 2 * np.pi, 400)
a = (x ** 2)
b = (x ** 3)
c = (x ** 4)
functions = [a,b,c]
label = "This is a long label for a legend and I try to fit to its ax"
fig, axs = plt.subplots(2, 2)
for y in functions :
axs[0, 0].plot(x, y, label=label)
axs[0, 1].plot(x, -y, label=label)
axs[1, 0].plot(x, y, label=label)
axs[1, 1].plot(x, -y, label=label)
for ax in axs.flat:
ax.set_title('Title')
ax.set(xlabel='x-label', ylabel='y-label')
ax.legend() # commented for the Figure 1 and active for the Figure 2
fig.tight_layout()
Thank you in advance.