Matplotlib legend
Python hosting: Host, run, and code Python in the cloud!
Matplotlib is a versatile Python library that provides native support for creating legends in various visualizations. Understanding how to position legends, whether inside or outside a chart, can enhance data interpretation. This article offers a comprehensive guide on leveraging the legend() function in matplotlib for enhancing your data visualizations.
Related Course:
Positioning the Matplotlib Legend Inside the Chart
Utilizing matplotlib’s legend()
function, one can seamlessly position the legend within the chart. Here’s a practical example:
import matplotlib.pyplot as plt |
Positioning the Matplotlib Legend at the Bottom
To move the legend to the bottom of your chart, you can adjust the legend()
parameters as shown:
ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.05), shadow=True, ncol=2) |
Note the introduction of the ncol=2
parameter, which sets the number of columns in the legend. Additionally, a shadow effect has been added for aesthetic purposes.
Complete code example:
import matplotlib.pyplot as plt |
Positioning the Matplotlib Legend at the Top
To shift the legend to the top of your visualization, modify the bbox_to_anchor
values:
ax.legend(loc='upper center', bbox_to_anchor=(0.5, 1.00), shadow=True, ncol=2) |
Complete code for this setup:
import matplotlib.pyplot as plt |
Placing the Legend Outside to the Right
To locate the legend externally on the right, we need to resize the plot and set the legend’s position relative to it:
chartBox = ax.get_position() |
Here’s a complete implementation:
import matplotlib.pyplot as plt |
To further enhance your matplotlib capabilities, download more examples. If you wish to explore other plotting techniques, you can navigate backward or forward.
Leave a Reply: