Keywords: Matplotlib | Legend | Font Size | bbox_to_anchor
Abstract: This article provides a comprehensive guide on positioning legends outside the plot area in Matplotlib without altering axes size, and methods to reduce legend font size for improved visualization. It covers the use of bbox_to_anchor and loc parameters for precise placement, along with fontsize adjustments via direct parameters or FontProperties. Rewritten code examples illustrate step-by-step implementation, supplemented by tips on subplot adjustment and tight_layout for enhanced plot clarity.
Overview of Legend Placement Issues
In data visualization, legends are essential for identifying plot elements, but placing them inside the plot area can obscure data. Positioning legends externally maintains data visibility without resizing axes. Matplotlib offers flexible parameters to achieve this, and this section introduces basic concepts and common requirements.
Using bbox_to_anchor and loc for External Placement
The bbox_to_anchor parameter allows specifying the legend's position outside the axes, combined with loc to define the anchor point of the legend box. For instance, placing the legend to the right of the plot area can be done with bbox_to_anchor=(1.05, 1) and loc='upper left', ensuring no overlap with data regions. The following code example demonstrates basic usage.
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(10)
fig, ax = plt.subplots()
for i in range(5):
ax.plot(x, i * x, label=f'y = {i}x')
ax.legend(loc='upper left', bbox_to_anchor=(1.05, 1))
plt.show()This code generates a simple plot with the legend positioned outside the upper right corner. Users can adjust coordinates, such as using (1.1, 0.5) to place the legend at the right center.
Adjusting Legend Font Size
To reduce the legend box size, the fontsize parameter can be used to set text size directly, or FontProperties class for finer control. Font size options include 'xx-small', 'x-small', etc., ensuring compact text without compromising readability. The following examples show two methods.
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
# Method 1: Using fontsize parameter
plt.plot([1, 2, 3], label='Line 1')
plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left', fontsize='xx-small')
plt.show()
# Method 2: Using FontProperties
font_prop = FontProperties()
font_prop.set_size('x-small')
plt.plot([1, 2, 3], label='Line 1')
plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left', prop=font_prop)
plt.show()These methods allow flexible font adjustments based on plot requirements, preventing the legend from occupying excessive space.
Complete Code Example and Integrated Techniques
Combining legend placement and font adjustment, the following example demonstrates a comprehensive application, including the use of tight_layout for automatic layout optimization to ensure full legend visibility.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
fig, ax = plt.subplots()
for i in range(3):
ax.plot(x, np.sin(x + i), label=f'Sin curve {i}')
ax.legend(loc='center left', bbox_to_anchor=(1, 0.5), fontsize='small')
plt.tight_layout()
plt.show()In this code, the legend is placed at the right center with smaller font size, and tight_layout optimizes the overall layout. Users can also manually adjust subplot parameters via subplots_adjust, e.g., plt.subplots_adjust(right=0.8) to reserve space for the legend.
Additional Practical Tips and Considerations
Beyond basic methods, Matplotlib supports using fig.legend for figure-wide legends or placing legends in dedicated subplot axes. For example, in multi-subplot scenarios, adjusting width ratios with gridspec_kw enables precise control over legend positioning. Additionally, saving figures with bbox_inches='tight' ensures all elements, including legends, are fully included. These techniques aid in handling complex visualization cases, enhancing code robustness and maintainability.
Summary and Best Practices
By effectively utilizing bbox_to_anchor, loc, and fontsize parameters, users can position legends outside the plot area and adjust font size to optimize data visualization. It is recommended to test various parameter combinations in practical applications and integrate automatic layout tools like tight_layout to balance aesthetics and functionality. The code examples provided in this guide are rewritten based on core concepts to facilitate deep understanding and flexible application of these techniques.