Home > Backend Development > Python Tutorial > How to Expand Figure Box to Accommodate Legends Outside the Axis in Matplotlib?

How to Expand Figure Box to Accommodate Legends Outside the Axis in Matplotlib?

Barbara Streisand
Release: 2024-10-18 12:18:30
Original
489 people have browsed it

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:

  1. bbox_extra_artists to include additional artists that extend beyond the axis, such as legends.
  2. bbox_inches='tight' to adjust the figure size to fit all the elements within it.

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>
Copy after login

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>
Copy after login

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!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template