Home >Backend Development >Python Tutorial >How to Expand Figure Box Size Dynamically to Accommodate an Expanding Legend in Matplotlib?

How to Expand Figure Box Size Dynamically to Accommodate an Expanding Legend in Matplotlib?

Susan Sarandon
Susan SarandonOriginal
2024-10-18 12:51:30585browse

How to Expand Figure Box Size Dynamically to Accommodate an Expanding Legend in Matplotlib?

Expanding Figure Box to Accommodate Exceeding Legend

Issue Description

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.

Dynamic Figure Box Expansion

The desired solution is to dynamically expand the size of the figure box to accommodate an expanding legend.

Implementation: Custom savefig Call with bbox_extra_artists

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.

Example and Result

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!

Statement:
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