Legends turn repeated colors, markers, or line styles into labels the reader can match to the data. A Matplotlib figure with multiple series becomes ambiguous when the plotted artists are not named in the figure itself.
Matplotlib builds an Axes legend from artists that carry a visible label. The common pattern is to set label= while plotting, call ax.legend() after the artists exist, and let Matplotlib draw one legend key and label for each included artist.
Place the legend where it does not cover the important data, and keep helper artists out of it with no label or an underscore-prefixed label. A saved PNG gives a direct check that the legend title, entries, and chosen corner render in non-interactive scripts.
Steps to add a legend in Matplotlib:
- Create a script that labels each plotted series and calls ax.legend() after the lines are drawn.
- legend_demo.py
import matplotlib.pyplot as plt months = ["Jan", "Feb", "Mar", "Apr"] north = [18, 22, 24, 28] south = [14, 18, 20, 23] target = [16, 20, 23, 26] fig, ax = plt.subplots(layout="constrained") ax.plot(months, north, marker="o", label="North region") ax.plot(months, south, marker="s", label="South region") ax.plot(months, target, linestyle="--", color="0.35", label="Target") legend = ax.legend(loc="upper left", title="Sales plan", ncols=1, frameon=True) ax.set_title("Quarterly bookings") ax.set_ylabel("Bookings") fig.savefig("legend-add-output.png", dpi=160) labels = ", ".join(text.get_text() for text in legend.get_texts()) print(f"Legend labels: {labels}") print("Saved figure: legend-add-output.png")
Calling ax.legend() without handles uses the labeled artists already attached to the Axes. Labels that are empty or start with an underscore are ignored, so helper lines can stay out of the legend.
- Run the script from the directory where the output image should be written.
$ python legend_demo.py Legend labels: North region, South region, Target Saved figure: legend-add-output.png
- Open the saved image and confirm each visible series has one legend entry in the selected corner.
If the legend covers important data, change loc="upper left" to another fixed location such as loc="lower right" and rerun the script.
Mohd Shakir Zakaria is a cloud architect with deep roots in software development and open-source advocacy. Certified in AWS, Red Hat, VMware, ITIL, and Linux, he specializes in designing and managing robust cloud and on-premises infrastructures.