How to Prevent Cut-off Legend in Matplotlib and Maintain Data Visibility?

Barbara Streisand
Release: 2024-10-18 12:20:03
Original
365 people have browsed it

How to Prevent Cut-off Legend in Matplotlib and Maintain Data Visibility?

Addressing Cut-off Legend in Matplotlib by Resizing the Figure Box

In Matplotlib, moving the legend outside the plot axis often results in its cutoff by the figure box. While shrinking the axis has been suggested as a solution, it diminishes data visibility, especially when presenting complex plots with numerous legend entries.

A more effective approach, as highlighted in Benjamin Root's response on the Matplotlib mailing list, involves modifying the savefig call to incorporate the legend as an extra artist:

fig.savefig('samplefigure', bbox_extra_artists=(lgd,), bbox_inches='tight')
Copy after login

This method, similar to using tight_layout, enables savefig to consider the legend when calculating the figure box size.

The following enhanced code sample demonstrates the solution:

import matplotlib.pyplot as plt
import numpy as np

plt.gcf().clear()
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')
handles, labels = ax.get_legend_handles_labels()
lgd = ax.legend(handles, labels, loc='upper center', bbox_to_anchor=(0.5,-0.1))
text = ax.text(-0.2,1.05, "Aribitrary text", transform=ax.transAxes)
ax.set_title("Trigonometry")
ax.grid('on')
fig.savefig('samplefigure', bbox_extra_artists=(lgd,text), bbox_inches='tight')
Copy after login

This now dynamically adjusts the figure box size to accommodate the legend, preventing its cutoff while maintaining data visibility.

The above is the detailed content of How to Prevent Cut-off Legend in Matplotlib and Maintain Data Visibility?. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!