Matplotlib legend() Function |
\\n\\n Matplotlib Reference Documentation
The legend() function is used to add a legend to a chart, helping readers identify the meaning of each curve or dataset.
Function Definition
\\n\\nmatplotlib.pyplot.legend(*args, **kwargs)\\nAxes.legend(*args, **kwargs)\\nFigure.legend(*args, **kwargs)\\n\\n\\nCommon Parameters
\\n\\n| Parameter | \\nType | \\nDescription | \\n
|---|---|---|
| loc | \\nstr or int | \\nLegend location: 'best' (automatic), 'upper right', 'upper left', 'lower left', 'lower right', 'right', 'center left', 'center right', 'lower center', 'upper center', 'center', 'outside' (outside) | \\n
| bbox_to_anchor | \\ntuple | \\nLegend anchor coordinates, used with loc for precise positioning. For example, (1.05, 1) places the legend in the upper-right corner outside the Axes. | \\n
| ncol | \\nint | \\nNumber of legend columns; default is 1. Multiple entries are displayed in multiple columns. | \\n
| fontsize | \\nint or str | \\nLegend font size, e.g., 10, 'small', 'large' | \\n
| frameon | \\nbool | \\nWhether to show the legend frame; default is True | \\n
| shadow | \\nbool | \\nWhether to add a shadow effect | \\n
| title | \\nstr | \\nLegend title | \\n
| facecolor | \\ncolor | \\nLegend background color | \\n
| edgecolor | \\ncolor | \\nLegend frame color | \\n
| fancybox | \\nbool | \\nWhether to use rounded frame corners; default is True | \\n
| markerscale | \\nfloat | \\nScaling factor for markers in the legend relative to the original markers | \\n
| handlelength | \\nfloat | \\nLength of line handles in the legend | \\n
\\n\\n\\nThe legend only displays Artists that have the
\\nlabelparameter set. A common practice is to directly specifylabelin plotting functions such asplot(),scatter(),bar(), and then calllegend().
\\n\\n
Usage Examples
\\n\\nExample 1: Basic Legend
\\n\\nExamples
\\n\\nimport matplotlib.pyplot as plt\\nimport numpy as np\\n\\nx = np.linspace(0,10,100)\\n\\nfig, ax = plt.subplots(layout='constrained')\\n\\n# The label for each curve is automatically added to the legend\\n ax.plot(x, np.sin(x), label='sin(x)')\\n ax.plot(x, np.cos(x), label='cos(x)')\\n ax.plot(x, np.sin(x) * np.exp(-x/3), label='damped sin(x)')\\n\\nax.legend(loc='upper right')# Automatically collect all labels\\n ax.set_title('Basic Legend')\\n ax.set_xlabel('x')\\n ax.grid(True, alpha=0.3)\\n\\n plt.show()\\n\\n\\nExample 2: Legend Outside the Plot + Multiple Columns
\\n\\nExamples
\\n\\nimport matplotlib.pyplot as plt\\nimport numpy as np\\n\\nx = np.linspace(0,10,100)\\n\\nfig, ax = plt.subplots(figsize=(8,4), layout='constrained')\\n\\n# Plot multiple curves\\nfor i in range(6):\\n ax.plot(x, np.sin(x + i * 0.5), label=f'sin(x + {i*0.5:.1f})')\\n\\n# Place the legend outside the Axes and display it in two columns\\n ax.legend(loc='upper left',\\n bbox_to_anchor=(1.02,1),# Outside upper right corner\\n ncol=2,# Display in two columns\\n title='Phase Shift',\\n frameon=True,\\n fancybox=True,\\n shadow=True)\\n\\nax.set_title('Legend Outside the Plot (ncol=2)')\\n ax.set_xlabel('x')\\n ax.grid(True, alpha=0.3)\\n\\n plt.show()\\n\\n\\nExample 3: Custom Legend Entries
\\n\\nExamples
\\n\\nimport matplotlib.pyplot as plt\\nimport matplotlib.patches as mpatches\\nimport numpy as np\\n\\nx = np.linspace(0,10,100)\\n\\nfig, ax = plt.subplots(layout='constrained')\\n\\nax.plot(x, np.sin(x),'b-', linewidth=2)\\n ax.plot(x, np.cos(x),'r--', linewidth=2)\\n\\n# Manually specify legend entries (not associated with plot labels)\\n blue_line = mpatches.Patch(color='blue', label='Sine Wave')\\n red_line = mpatches.Patch(color='red', label='Cosine Wave')\\n\\nax.legend(handles=[blue_line, red_line],\\n loc='upper right',\\n fontsize=11)\\n\\nax.set_title('Custom Legend Handles')\\n ax.set_xlabel('x')\\n ax.grid(True, alpha=0.3)\\n\\n plt.show()\\n\\n\\nExample 4: Legend Location Quick Reference
\\n\\nExamples
\\n\\nimport matplotlib.pyplot as plt\\n\\n# Show the positions corresponding to all loc codes\\n locations =[\\n'upper left','upper right','lower left','lower right',\\n'center left','center right','lower center','upper center',\\n'center'\\n]\\n\\nfig, axes = plt.subplots(3,3, figsize=(10,8),\\n layout='constrained')\\n\\n axes = axes.flatten()\\n\\nfor ax, loc in zip(axes, locations):\\n ax.plot([0,1],[0,1],'b-', label='Line A')\\n ax.plot([0,1],[1,0],'r--', label='Line B')\\n ax.legend(loc=loc, fontsize=8, title=f'loc="{loc}"')\\n ax.set_xticks([])\\n ax.set_yticks([])\\n\\nfig.suptitle('All legend() Locations', fontsize=14)\\n\\n plt.show()\\n\\n\\n\\n\\n
Frequently Asked Questions
\\n\\nLegend Not Showing?
\\n\\n- \\n
- Check whether the plotting functions have the
labelparameter set. \\n - Ensure that the
legend()function is called. \\n - If certain Artists should not appear in the legend, set their
labelto an empty string or'_nolegend_'. \\n
How to Partially Modify Line Styles in the Legend?
\\n\\nRetrieve the line objects in the legend via legend.get_lines() and modify their properties, or use the handler_map parameter.
YouTip