YouTip LogoYouTip

Matplotlib Ref Legend

Matplotlib legend() Function |

\\n\\n

Image 1: Matplotlib Reference Documentation Matplotlib Reference Documentation

\\n\\n

The legend() function is used to add a legend to a chart, helping readers identify the meaning of each curve or dataset.

\\n\\n

Function Definition

\\n\\n
matplotlib.pyplot.legend(*args, **kwargs)\\nAxes.legend(*args, **kwargs)\\nFigure.legend(*args, **kwargs)\\n
\\n\\n

Common Parameters

\\n\\n\\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n
ParameterTypeDescription
locstr or intLegend location: 'best' (automatic), 'upper right', 'upper left', 'lower left', 'lower right', 'right', 'center left', 'center right', 'lower center', 'upper center', 'center', 'outside' (outside)
bbox_to_anchortupleLegend anchor coordinates, used with loc for precise positioning. For example, (1.05, 1) places the legend in the upper-right corner outside the Axes.
ncolintNumber of legend columns; default is 1. Multiple entries are displayed in multiple columns.
fontsizeint or strLegend font size, e.g., 10, 'small', 'large'
frameonboolWhether to show the legend frame; default is True
shadowboolWhether to add a shadow effect
titlestrLegend title
facecolorcolorLegend background color
edgecolorcolorLegend frame color
fancyboxboolWhether to use rounded frame corners; default is True
markerscalefloatScaling factor for markers in the legend relative to the original markers
handlelengthfloatLength of line handles in the legend
\\n\\n
\\n

The legend only displays Artists that have the label parameter set. A common practice is to directly specify label in plotting functions such as plot(), scatter(), bar(), and then call legend().

\\n
\\n\\n
\\n\\n

Usage Examples

\\n\\n

Example 1: Basic Legend

\\n\\n

Examples

\\n\\n
import 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\\n

Example 2: Legend Outside the Plot + Multiple Columns

\\n\\n

Examples

\\n\\n
import 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\\n

Example 3: Custom Legend Entries

\\n\\n

Examples

\\n\\n
import 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\\n

Example 4: Legend Location Quick Reference

\\n\\n

Examples

\\n\\n
import 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\\n

Legend Not Showing?

\\n\\n
    \\n
  • Check whether the plotting functions have the label parameter set.
  • \\n
  • Ensure that the legend() function is called.
  • \\n
  • If certain Artists should not appear in the legend, set their label to an empty string or '_nolegend_'.
  • \\n
\\n\\n

How to Partially Modify Line Styles in the Legend?

\\n\\n

Retrieve the line objects in the legend via legend.get_lines() and modify their properties, or use the handler_map parameter.

\\n\\n

Image 2: Matplotlib Reference Documentation Matplotlib Reference Documentation

← Matplotlib Ref PlotMatplotlib Ref Labels β†’