Home >Backend Development >Python Tutorial >How to Position a Matplotlib Legend Outside the Plot Area and Customize its Size?

How to Position a Matplotlib Legend Outside the Plot Area and Customize its Size?

DDD
DDDOriginal
2024-12-29 00:51:10247browse

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:

  • loc parameter: The loc parameter allows you to specify the location of the legend inside the plot. By setting loc to upper center or lower center, you can move the legend to the top or bottom of the plot.
  • ncol parameter: The ncol parameter controls the number of columns in the legend. By specifying more columns, you can spread out the legend and reduce its overall height.
  • fancybox and shadow parameters: The fancybox and shadow parameters can be used to add aesthetic effects to the legend, such as rounded corners and a drop shadow.

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!

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