Matplotlib Labels and Title
Titles, axis labels, and legends turn a bare chart into one that explains itself.
Adding a title and axis labels
plt.title() places a heading above the plot describing what the chart shows at a glance, while plt.xlabel() and plt.ylabel() describe what each axis represents, ideally including its unit of measurement. All three simply take a string and should be called before plt.show().
Example
import matplotlib.pyplot as plt
months = [1, 2, 3, 4, 5, 6]
sales = [200, 220, 250, 210, 300, 280]
plt.plot(months, sales)
plt.title("Monthly Sales")
plt.xlabel("Month")
plt.ylabel("Sales ($ thousands)")
plt.show()Styling text with fontdict
plt.title(), plt.xlabel(), and plt.ylabel() all accept a fontdict argument: a dictionary describing font properties such as family, color, and size. plt.title() also accepts a loc argument that positions the title, for example "left", "center", or "right".
Example
import matplotlib.pyplot as plt
font_title = {"family": "serif", "color": "darkred", "size": 18}
font_labels = {"family": "serif", "color": "darkblue", "size": 13}
plt.plot([1, 2, 3, 4], [10, 15, 13, 18])
plt.title("Growth Trend", fontdict=font_title, loc="left")
plt.xlabel("Week", fontdict=font_labels)
plt.ylabel("Score", fontdict=font_labels)
plt.show()Adding a legend
When a chart has more than one line, give each plt.plot() call a label argument, then call plt.legend() once to draw a box identifying which line is which.
Example
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
plt.plot(x, [1, 2, 3, 4, 5], label="Linear")
plt.plot(x, [1, 4, 9, 16, 25], label="Squared")
plt.legend()
plt.show()- plt.title(text, fontdict=None, loc="center") adds a title
- plt.xlabel(text) and plt.ylabel(text) label the axes
- fontdict keys commonly used: family, color, size
- label="..." inside plt.plot() feeds plt.legend()
Exercise: Matplotlib Labels and Title
Which function sets the label text for the x-axis?