I tried to make a plot with two subplots but only one legend since the two subplots express the same set of information.
I put the legend outside of the two subplots for better interpretation. I have found that by using fig.legend instead of
the ax.legend method. In the saved plot, the legend box are just cut off.
I tried to fix this by using bbox_extra_artists argument in the savefig method, following the instruction
But it does not work. The following code illustrate the problem,
import matplotlib.pyplot as plt
import numpy as np
import matplotlib as mpl
x = np.arange(-5, 5, 0.1)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = np.sin(2*x)
y4 = np.cos(2*x)
fig, (ax1, ax2) = plt.subplots(ncols=1, nrows=2, figsize=(10, 6))
ax1.plot(x, y1, label='sin')
ax1.plot(x, y2, label='cos')
ax2.plot(x, y3, label='sin')
ax2.plot(x, y4, label='cos')
handles, labels = ax1.get_legend_handles_labels()
# legend = fig.legend(handles, labels, loc='lower left', ncol=2, frameon=False,
# bbox_to_anchor=(0.12, 0.88))
# plt.savefig('test.jpg', bbox_extra_artists=(legend,), bbox_inches='tight')
legend = ax1.legend(handles, labels, ncol=2, frameon=False,
loc='lower left', bbox_to_anchor=(-0.01, 1.0))
If I use the above code, the generated image is fine. But if I use the commented code instead, the legend is gone in the generated image.
-------------- next part --------------
An HTML attachment was scrubbed...