In Matplotlib, moving the legend outside the plot axis often results in its cutoff by the figure box. While shrinking the axis has been suggested as a solution, it diminishes data visibility, especially when presenting complex plots with numerous legend entries.
A more effective approach, as highlighted in Benjamin Root's response on the Matplotlib mailing list, involves modifying the savefig call to incorporate the legend as an extra artist:
fig.savefig('samplefigure', bbox_extra_artists=(lgd,), bbox_inches='tight')
This method, similar to using tight_layout, enables savefig to consider the legend when calculating the figure box size.
The following enhanced code sample demonstrates the solution:
import matplotlib.pyplot as plt import numpy as np plt.gcf().clear() x = np.arange(-2*np.pi, 2*np.pi, 0.1) fig = plt.figure(1) ax = fig.add_subplot(111) ax.plot(x, np.sin(x), label='Sine') ax.plot(x, np.cos(x), label='Cosine') ax.plot(x, np.arctan(x), label='Inverse tan') handles, labels = ax.get_legend_handles_labels() lgd = ax.legend(handles, labels, loc='upper center', bbox_to_anchor=(0.5,-0.1)) text = ax.text(-0.2,1.05, "Aribitrary text", transform=ax.transAxes) ax.set_title("Trigonometry") ax.grid('on') fig.savefig('samplefigure', bbox_extra_artists=(lgd,text), bbox_inches='tight')
This now dynamically adjusts the figure box size to accommodate the legend, preventing its cutoff while maintaining data visibility.
The above is the detailed content of How to Prevent Cut-off Legend in Matplotlib and Maintain Data Visibility?. For more information, please follow other related articles on the PHP Chinese website!