Home >Backend Development >Python Tutorial >How to Expand Figure Box Size Dynamically to Accommodate an Expanding Legend in Matplotlib?
When placing a legend outside of the axis in Matplotlib, it can occasionally extend beyond the boundaries of the figure box, resulting in a cutoff appearance. Resizing the axis axes by shrinking them is not an optimal solution, as it diminishes the data's visibility.
The desired solution is to dynamically expand the size of the figure box to accommodate an expanding legend.
To achieve this, the savefig function call can be adjusted to include the bbox_extra_artists argument:
<code class="python">fig.savefig('samplefigure', bbox_extra_artists=(lgd,), bbox_inches='tight')</code>
This specifies that the figure box should consider extra artists, such as the legend (lgd), when calculating its size.
Using this modified savefig call:
<code class="python">import matplotlib.pyplot as plt import numpy as np fig = plt.figure(1) ax = fig.add_subplot(111) ax.set_title("Trigonometry") 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') lgd = ax.legend(loc='upper center', bbox_to_anchor=(0.5,-0.1)) ax.grid('on') fig.savefig('samplefigure', bbox_extra_artists=(lgd,), bbox_inches='tight')</code>
Produces a figure with the legend extending beyond the axis but accommodated within the expanded figure box:
Trigonometry 2 1 0 -1 -2 -4π -2π 0 2π 4π Inverse tan Cosine Sine
The above is the detailed content of How to Expand Figure Box Size Dynamically to Accommodate an Expanding Legend in Matplotlib?. For more information, please follow other related articles on the PHP Chinese website!