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
Release: 2024-10-18 12:51:30
Original
620 people have browsed it

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

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

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

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