Matplotlib Labels

Labels are essential for making your plots understandable. Matplotlib allows you to add titles, axis labels, and legends to your plots, helping to convey the meaning of the data visually.

Adding Titles

You can add a title to your plot using the plt.title() function. A well-placed title provides context to your plot, making it easier for viewers to understand what the data represents:

Python
import matplotlib.pyplot as plt

x = [0, 1, 2, 3, 4]
y = [0, 1, 4, 9, 16]

plt.plot(x, y)
plt.title("Sample Plot")
plt.show()

In this example, plt.title("Sample Plot") adds a title above the plot, providing context to the data being displayed.

Adding Axis Labels

Use plt.xlabel() and plt.ylabel() to add labels to the x and y axes, respectively. These labels describe what each axis represents:

Python
plt.xlabel("X-axis Label")
plt.ylabel("Y-axis Label")
plt.show()

In this example, plt.xlabel("X-axis Label") labels the horizontal axis, while plt.ylabel("Y-axis Label") labels the vertical axis, making the plot more informative.

Adding a Legend

If your plot contains multiple data series, you can add a legend to identify each series. The plt.legend() function is used for this purpose:

Python
plt.plot(x, y, label="Series 1")
plt.legend()
plt.show()

The label="Series 1" argument in plt.plot() assigns a label to the data series, and plt.legend() displays this label in the plot. The legend helps to distinguish between different data series, especially in more complex plots.

Customizing the Legend

You can customize the appearance and position of the legend using additional parameters in the plt.legend() function. For example, you can specify the location, fontsize, and more:

Python
plt.legend(loc="upper left", fontsize="small")
plt.show()

This example positions the legend in the upper left corner of the plot and sets a smaller font size.

By effectively using titles, axis labels, and legends, you can create clear and informative plots that are easy for others to interpret.