Home >Backend Development >Python Tutorial >How to Position a Matplotlib Legend Outside the Plot Area and Customize its Size?
How to Position the Legend Outside the Plot Area
Problem:
You want to create multiple plots in a single figure, but you need the legend to be positioned outside of the plot area. Additionally, you want to minimize the size of the legend by reducing the font size.
Solution:
1. Using bbox_to_anchor:
The bbox_to_anchor keyword argument allows you to specify the location of the legend box relative to the plot axes. By setting bbox_to_anchor to (1.1, 1.05), you can shift the legend slightly outside the axes boundaries:
ax.legend(bbox_to_anchor=(1.1, 1.05))
2. Shrinking the Plot Area:
Another method is to shrink the current plot's width or height and position the legend accordingly. For example, to shrink the plot's width by 20% and place the legend outside the axis on the right:
# Shrink current axis by 20% box = ax.get_position() ax.set_position([box.x0, box.y0, box.width * 0.8, box.height]) # Put a legend to the right of the current axis ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))
3. Reducing Legend Font Size:
To reduce the size of the legend box, you can use the fontsize parameter in the legend() method:
ax.legend(fontsize=8)
4. Alternative Methods:
For more information on customizing legends, refer to the matplotlib documentation: https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.legend.html
The above is the detailed content of How to Position a Matplotlib Legend Outside the Plot Area and Customize its Size?. For more information, please follow other related articles on the PHP Chinese website!