Change the legend position in Matplotlib
0 1140
Introduction to Changing Legend Position in Matplotlib
Legends help viewers understand what each line, bar, or shape in a plot represents. Matplotlib provides a simple way to control where the legend appears. Whether you want it inside, outside, or in a specific corner of your plot, it's all possible with a few parameters.
Using the loc Parameter
The easiest way to move the legend is by using the loc argument. This tells Matplotlib where to place the legend box. There are several predefined positions like:
'upper right'(default)'lower left''center''upper left''lower right'
import matplotlib.pyplot as plt
x = [0, 1, 2]
y1 = [1, 2, 3]
y2 = [3, 2, 1]
plt.plot(x, y1, label='Line A')
plt.plot(x, y2, label='Line B')
plt.legend(loc='lower left') # Moves legend to lower left
plt.show()
Placing the Legend Outside the Plot
If your plot is crowded, you can move the legend outside the axes area using the bbox_to_anchor parameter. This lets you define exact coordinates for the legend.
plt.legend(loc='upper left', bbox_to_anchor=(1.05, 1))
The legend is now placed outside the top-left corner. You can change the anchor point values to position it elsewhere.
Handling Layout Issues
When moving the legend outside the plot, parts of it may get cut off. To fix this, use tight_layout() or adjust the figure size manually.
plt.tight_layout()
This automatically adjusts spacing to ensure everything fits within the visible area.
Customizing Appearance Along with Position
Alongside location, you can style the legend box using options like:
shadow=Trueframeon=Falsefancybox=Truetitle="Legend Title"
plt.legend(loc='center right', shadow=True, fancybox=True, title="Lines")
Conclusion
Controlling the position of the legend in Matplotlib makes your plots more readable and visually balanced. With just a few adjustments using loc and bbox_to_anchor, you can place the legend exactly where it makes the most sense for your data story.
For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!
Share:


Comments
Waiting for your comments