Matplotlib Labels
Craft readable charts by configuring titles, axis labels, tick formatting, and legends.
Titles and Axis Labels
ax.set_title("Monthly Revenue", fontsize=16, pad=12)
ax.set_xlabel("Month", fontsize=12)
ax.set_ylabel("Revenue ($)", fontsize=12)Use labelpad to add extra spacing when tick labels are dense.
Tick Formatting
Customize tick labels with formatters for dates, currency, or percentages.
from matplotlib.ticker import FuncFormatter
ax.yaxis.set_major_formatter(FuncFormatter(lambda value, _: f"${value:,.0f}"))Rotate labels with ax.set_xticklabels(..., rotation=45) to prevent overlap.
Legends
Provide descriptive labels to plot() and call ax.legend().
ax.legend(title="Region", loc="upper left", frameon=False)For complex legends, position them outside the axes using bbox_to_anchor.
Annotations and Text
Add free-form text with ax.text() or use ax.annotate() for labeled arrows.
ax.text(0.05, 0.95, "FY24", transform=ax.transAxes, fontsize=12, fontweight="bold")Combine annotations with markers to highlight business targets distributed via info.studygrid@gmail.com.
Accessibility Considerations
- Use descriptive titles and axis names.
- Ensure sufficient color contrast between labels and background.
- Include units and data sources in captions.
Next Steps
Learn how to manage gridlines to improve chart readability without overwhelming the data.
Titles, Axis Labels, and Fonts
import matplotlib.pyplot as plt
font = {"color": "darkblue", "size": 14}
plt.plot([1, 2, 3], [10, 20, 15])
plt.title("Sales Over Time", fontdict=font, loc="left")
plt.xlabel("Month")
plt.ylabel("Revenue ($)")
plt.show()loc positions the title ("left", "center", "right"). Use plt.suptitle() for an overall title above subplots.
Try It Yourself
Exercise: Plot any data and label the x-axis "Day", the y-axis "Temperature", with the title "Weather".
Show solution
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [15, 18, 12])
plt.title("Weather")
plt.xlabel("Day"); plt.ylabel("Temperature")
plt.show()Key Takeaways
- Label every chart:
title,xlabel,ylabel. - Style text with
fontdictand position withloc.
📘 Real-World Deep Dive
Knowing <strong>Matplotlib Labels (Matplotlib)</strong> well is what turns Matplotlib from a curiosity into a daily tool — you'll reach for it in nearly every real project.
Real-Life Scenario
An end-to-end usage of Matplotlib Labels that you'd actually see in a data pipeline or analytics notebook.
Real-Life Example
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [4, 5, 6])
plt.title("My chart")
plt.xlabel("x axis"); plt.ylabel("y axis")
plt.show()Expected Output
(no output)Common mistakes
- Calling
plt.plotwithoutplt.show()in scripts (orplt.savefig) produces no visible output. - Passing mismatched array shapes to
plt.plot(x, y)raises a uselessValueError— verify shapes withx.shapeandy.shapefirst. - Mixing
numpy.float64withpandas.Seriesis OK, but mixingnumpy.datetime64with Pythondatetime.dateneeds an explicit cast. - Treating Matplotlib Labels as a black box without reading the docs — the API has subtle defaults that bite when you scale.
🚀 Performance & Best Practices
- For large scatter plots use
plt.scatter(..., s=1, rasterised=True)or switch todatashader. - Use the
aggbackend on web services:import matplotlib; matplotlib.use("Agg"). - Plot once and reuse the figure: avoid embedding Matplotlib into tight Python loops without an explicit
clear(). - When working with Matplotlib, prefer vectorised / batched operations over Python loops.
🧪 Try It Yourself
- Reproduce the snippet on a representative slice of your own data.
- Profile the snippet with
cProfileortimeitand find the single biggest improvement. - Generalise the snippet into a small, reusable function you can drop into future projects.