0
0
MatplotlibDebug / FixBeginner · 3 min read

How to Fix Legend Not Showing in Matplotlib: Quick Solutions

The legend in matplotlib does not show if you forget to call plt.legend() after plotting or if you don't provide labels for your plot elements. Always add label='name' in your plot commands and call plt.legend() to display the legend.
🔍

Why This Happens

The legend does not appear because matplotlib needs two things: labels for the plot elements and a command to display the legend. If you plot lines or points without label arguments, matplotlib has nothing to show in the legend. Also, if you forget to call plt.legend(), the legend will not be drawn on the plot.

python
import matplotlib.pyplot as plt

plt.plot([1, 2, 3], [4, 5, 6])
plt.plot([1, 2, 3], [6, 5, 4])
plt.show()
Output
A plot with two lines but no legend shown.
🔧

The Fix

Add label to each plot call to name the lines, then call plt.legend() to show the legend box. This tells matplotlib what to display and where.

python
import matplotlib.pyplot as plt

plt.plot([1, 2, 3], [4, 5, 6], label='Line 1')
plt.plot([1, 2, 3], [6, 5, 4], label='Line 2')
plt.legend()
plt.show()
Output
A plot with two lines and a legend box showing 'Line 1' and 'Line 2'.
🛡️

Prevention

Always provide label for each plot element you want in the legend. Call plt.legend() after all plotting commands. Use consistent labeling and check your plot visually to confirm the legend appears. This habit avoids missing legends in your graphs.

⚠️

Related Errors

Sometimes the legend appears but is empty because labels are empty strings or None. Also, legends can be hidden behind other plot elements if loc is set incorrectly. Fix these by ensuring labels are non-empty strings and adjusting legend position with plt.legend(loc='best').

Key Takeaways

Always add a label to each plot element you want in the legend.
Call plt.legend() after plotting to display the legend.
Check your plot visually to confirm the legend appears.
Use plt.legend(loc='best') to position the legend automatically.
Empty or missing labels cause the legend to be empty or invisible.