How to Fix Legend Not Showing in Matplotlib: Quick Solutions
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.
import matplotlib.pyplot as plt plt.plot([1, 2, 3], [4, 5, 6]) plt.plot([1, 2, 3], [6, 5, 4]) plt.show()
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.
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()
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').