Home >Backend Development >Python Tutorial >How to Expand Figure Box to Accommodate Legends Outside the Axis in Matplotlib?
Expanding Figure Box for Legends Outside of Axis
Moving a legend outside the axis often results in the figure box being too small to accommodate the legend's size. Shrinking the axis is not ideal as it reduces plot size, making it harder to interpret complex data.
Dynamic Figure Box Resizing
To solve this issue, it is possible to dynamically adjust the size of the figure box to fit the legend. This can be achieved by modifying the savefig() call with the following arguments:
Code Example
Consider the following code:
<code class="python">import matplotlib.pyplot as plt import numpy as np # Construct a plot with a legend 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') lgd = ax.legend(loc=9, bbox_to_anchor=(0.5,0)) ax.grid('on') # Save the figure with the adjusted bounding box fig.savefig('samplefigure', bbox_extra_artists=(lgd,), bbox_inches='tight')</code>
Output
This code will create a plot with a legend outside the axis and the figure box will expand to accommodate the legend. It is also possible to include additional artists, such as text labels, within the bbox_extra_artists argument.
Simplified Command
In recent versions of Matplotlib, the command has been simplified. To save a figure with a tight bounding box, only the following argument is needed:
<code class="python">plt.savefig('x.png', bbox_inches='tight')</code>
The above is the detailed content of How to Expand Figure Box to Accommodate Legends Outside the Axis in Matplotlib?. For more information, please follow other related articles on the PHP Chinese website!