Chapter 10 – Adding Legends, Titles, and Labels in Matplotlib
A data visualization is incomplete without proper context — and that comes from well-placed titles, labels, and legends. These elements make your charts understandable and professional. In this chapter, you’ll learn how to use Matplotlib’s powerful labeling and legend features effectively.
✅ Why Titles, Labels, and Legends Matter
Titles describe the overall plot, axis labels define what the axes represent, and legends clarify what each plotted line or marker means. Together, they make your charts self-explanatory.
✅ What You’ll Learn
- How to add and format plot titles
- How to label the X and Y axes
- How to create and customize legends
- How to adjust font styles, colors, and placement
- How to combine all elements for a publication-quality chart
✅ 1. Adding Titles to a Plot
Adding a title gives viewers immediate context. You can use plt.title() or the object-oriented version ax.set_title().
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [10, 8, 6, 4, 2]
plt.plot(x, y)
plt.title("Simple Line Plot Example")
plt.show()
You can also control font size, color, and alignment:
plt.title("Customized Title Example",
fontsize=14, color="darkred", loc="left")
- fontsize – changes text size
- color – sets title color
- loc – defines alignment: ‘left’, ‘center’, or ‘right’
✅ 2. Labeling Axes
Axis labels define what the X and Y values mean.
Use plt.xlabel() and plt.ylabel() (state-based) or ax.set_xlabel() and ax.set_ylabel() (object-oriented).
plt.plot(x, y)
plt.xlabel("Time (seconds)")
plt.ylabel("Distance (meters)")
plt.title("Object Motion Over Time")
plt.show()
You can customize label fonts just like the title:
plt.xlabel("Time (s)", fontsize=12, color="blue", labelpad=10)
plt.ylabel("Distance (m)", fontsize=12, color="green", labelpad=10)
The labelpad parameter adds padding between the axis and its label.
✅ 3. Adding Legends
Legends help distinguish multiple data series in the same plot. Use label= in your plot command and plt.legend() to display it.
plt.plot([1, 2, 3], [1, 2, 3], label="Line 1", color="blue")
plt.plot([1, 2, 3], [3, 2, 1], label="Line 2", color="red")
plt.title("Legend Example")
plt.xlabel("X-Axis")
plt.ylabel("Y-Axis")
plt.legend()
plt.show()
You can position the legend and customize its look:
plt.legend(loc="upper right", title="Lines", shadow=True, fontsize=10)
Common loc options include:
- “upper right”
- “upper left”
- “lower right”
- “lower left”
- “center”
- “best” (automatic placement)
You can also place the legend outside the main plot:
plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left', borderaxespad=0.)
plt.tight_layout()
plt.show()
✅ 4. Styling Fonts and Colors
Matplotlib lets you use different fonts and text effects to match your theme.
plt.title("Sales Report", fontweight="bold", fontstyle="italic", color="darkblue")
plt.xlabel("Quarter", fontsize=12, fontname="Comic Sans MS")
plt.ylabel("Revenue ($)", fontsize=12, fontname="Arial")
✅ 5. Adding Text and Annotations
Sometimes you may want to add small notes or highlight a specific point.
Use plt.text() or plt.annotate().
plt.plot([1, 2, 3, 4], [2, 4, 6, 8], label="Growth")
plt.text(3, 6.5, "Peak Point", color="darkred", fontsize=10)
plt.annotate("Important Rise", xy=(2, 4), xytext=(2.5, 6),
arrowprops=dict(facecolor='black', arrowstyle="->"))
plt.legend()
plt.show()
✅ 6. Combining Everything Together
Let’s combine all elements into a complete, styled plot.
import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
sales_2023 = [100, 120, 150, 180]
sales_2024 = [110, 130, 170, 200]
plt.plot(x, sales_2023, label="2023", color="blue", marker="o")
plt.plot(x, sales_2024, label="2024", color="orange", marker="s")
plt.title("Quarterly Sales Comparison", fontsize=16, fontweight="bold")
plt.xlabel("Quarter")
plt.ylabel("Sales ($)")
plt.legend(loc="upper left", title="Year", shadow=True)
plt.grid(True, linestyle=":", linewidth=0.8)
plt.tight_layout()
plt.show()
✅ Best Practices
- Keep labels concise yet descriptive.
- Always include units where applicable (e.g., seconds, meters, dollars).
- Use legends when plotting multiple datasets.
- Ensure fonts are readable even when the chart is resized.
- Use consistent style across all plots for a professional look.
✅ Summary
In this chapter, you learned how to enhance your visualizations with titles, axis labels, legends, and annotations. These elements make your plots easy to interpret and publication-ready.
In the next chapter, we’ll move on to Working with Images and Colors in Matplotlib — learning how to display images, use color maps, and apply colorbars effectively.
