Putting the legend outside the plot helps keep the plot area clear and easy to read. It avoids covering important data points.
0
0
Legend outside the plot in Matplotlib
Introduction
When the legend has many items and takes too much space inside the plot.
When data points are dense and the legend overlaps them.
When you want a cleaner look with more space for the data visualization.
When preparing plots for presentations or reports where clarity is important.
Syntax
Matplotlib
plt.legend(loc='best', bbox_to_anchor=(x, y), borderaxespad=pad)loc sets the anchor point of the legend box.
bbox_to_anchor moves the legend box outside the plot by specifying coordinates.
Examples
Places the legend outside the plot on the upper right side.
Matplotlib
plt.legend(loc='upper left', bbox_to_anchor=(1, 1))
Places the legend centered vertically on the right side outside the plot.
Matplotlib
plt.legend(loc='center left', bbox_to_anchor=(1, 0.5))
Places the legend outside the plot at the bottom right corner.
Matplotlib
plt.legend(loc='lower left', bbox_to_anchor=(1, 0))
Sample Program
This code plots two lines and places the legend outside the plot area on the right side, centered vertically. The bbox_to_anchor moves the legend box outside the plot, and tight_layout() adjusts the plot to fit everything nicely.
Matplotlib
import matplotlib.pyplot as plt x = [1, 2, 3, 4] y1 = [10, 20, 25, 30] y2 = [15, 18, 22, 27] plt.plot(x, y1, label='Line 1') plt.plot(x, y2, label='Line 2') # Put legend outside the plot on the right plt.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.title('Plot with Legend Outside') plt.xlabel('X axis') plt.ylabel('Y axis') plt.tight_layout() # Adjust layout to make room for legend plt.show()
OutputSuccess
Important Notes
Use plt.tight_layout() or adjust figure size to prevent clipping of the legend.
You can change bbox_to_anchor coordinates to move the legend to different outside positions.
Summary
Legends can be placed outside the plot to keep the plot area clear.
Use loc and bbox_to_anchor together to position the legend outside.
Adjust layout with tight_layout() to avoid overlap or clipping.