Adding labels and a title to your Matplotlib plot is straightforward. These elements help make your plot more understandable by providing context to the data being visualized. Below are examples and explanations of how to add and customize labels and titles.
Basic Example
Here’s a basic example that includes a title and labels for the x and y axes:
import matplotlib.pyplot as plt
# Sample data
x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]
# Create the plot
plt.plot(x, y)
# Add title and labels
plt.title("Simple Line Plot")
plt.xlabel("X Axis")
plt.ylabel("Y Axis")
# Show the plot
plt.show()
Customizing Labels and Title
You can further customize the appearance of the title and labels by using additional parameters in the title()
, xlabel()
, and ylabel()
functions.
import matplotlib.pyplot as plt
# Sample data
x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]
# Create the plot
plt.plot(x, y)
# Add title and labels with customization
plt.title("Simple Line Plot", fontsize=14, fontweight='bold', color='blue')
plt.xlabel("X Axis", fontsize=12, color='green')
plt.ylabel("Y Axis", fontsize=12, color='green')
# Show the plot
plt.show()
Adding Grid, Legends, and Annotations
For a more comprehensive plot, you might want to add a grid, legends, and annotations.
import matplotlib.pyplot as plt
# Sample data
x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]
# Create the plot
plt.plot(x, y, label='Prime Numbers', color='purple', marker='o')
# Add title and labels with customization
plt.title("Simple Line Plot", fontsize=14, fontweight='bold', color='blue')
plt.xlabel("X Axis", fontsize=12, color='green')
plt.ylabel("Y Axis", fontsize=12, color='green')
# Add grid
plt.grid(True)
# Add legend
plt.legend(loc='upper left')
# Add annotation
plt.annotate('Max Value', xy=(5, 11), xytext=(4, 10),
arrowprops=dict(facecolor='black', shrink=0.05))
# Show the plot
plt.show()