Matplotlib Labels
In Matplotlib, labels are an essential part of making plots clear and informative. Labels include the title of the plot, labels for the x-axis and y-axis, and other annotations that describe different elements of the plot. Here’s how to work with various labels in Matplotlib.
1. Title of the Plot
To add a title to your plot, use plt.title().
import matplotlib.pyplot as plt
# Data
x = [1, 2, 3, 4, 5]
y = [10, 20, 25, 30, 40]
# Plot
plt.plot(x, y)
# Add title
plt.title("My Line Plot")
plt.show()
Customizing the Title
You can customize the title by changing the font size, color, position, and more:
plt.title("Customized Plot Title", fontsize=16, color='blue', loc='left')
fontsize: Changes the font size.color: Sets the color of the title.loc: Sets the title alignment. The options are'center'(default),'left', or'right'.
2. Axis Labels
To add labels to the x-axis and y-axis, use plt.xlabel() and plt.ylabel().
plt.plot(x, y)
# Add labels
plt.xlabel("X Axis Label")
plt.ylabel("Y Axis Label")
plt.show()
Customizing Axis Labels
You can also customize axis labels similarly to titles:
plt.xlabel("X Axis Label", fontsize=14, color='green')
plt.ylabel("Y Axis Label", fontsize=14, color='purple')
3. Ticks and Tick Labels
Ticks are the marks along the x and y axes that show intervals. You can customize their appearance using plt.xticks() and plt.yticks().
Setting Custom Tick Labels
You can define custom tick labels on the x and y axes:
# Data
x = [1, 2, 3, 4, 5]
y = [10, 20, 25, 30, 40]
# Plot
plt.plot(x, y)
# Custom ticks for the x-axis
plt.xticks([1, 2, 3, 4, 5], ['A', 'B', 'C', 'D', 'E'])
# Custom ticks for the y-axis
plt.yticks([10, 20, 30, 40], ['Low', 'Medium', 'High', 'Very High'])
plt.show()
This will replace the numeric ticks with custom labels like 'A', 'B', 'C' for the x-axis and 'Low', 'Medium', etc., for the y-axis.
Rotating Tick Labels
You can rotate tick labels to avoid overlap, especially for long labels:
plt.xticks(rotation=45)
plt.yticks(rotation=90)
4. Adding Legends
Legends are used to describe the data series in the plot. You can add a legend using plt.legend().
# Data
x = [1, 2, 3, 4, 5]
y1 = [10, 20, 25, 30, 40]
y2 = [5, 15, 20, 25, 35]
# Plot two lines with labels
plt.plot(x, y1, label="Line 1")
plt.plot(x, y2, label="Line 2")
# Add legend
plt.legend()
plt.show()
Customizing Legends
You can customize the location, font size, and style of the legend:
plt.legend(loc='upper left', fontsize=12, title='Legend Title', title_fontsize='13')
loc: Controls the position of the legend ('upper left','upper right','lower left', etc.).fontsize: Sets the font size of the legend.title: Adds a title to the legend.title_fontsize: Sets the font size of the legend title.
5. Annotations
Annotations allow you to add notes or explanations to specific points on your plot using plt.annotate().
plt.plot(x, y)
# Annotate a specific point
plt.annotate('Highest Point', xy=(4, 30), xytext=(3, 35),
arrowprops=dict(facecolor='black', shrink=0.05))
plt.show()
In this example, the xy parameter specifies the point to annotate, and xytext specifies the position of the annotation text. The arrowprops argument adds an arrow pointing to the annotated point.
6. Multiline Labels
Sometimes, labels need to span multiple lines. You can use \n to create multiline labels:
plt.title("This is the Title\nwith Two Lines", fontsize=14)
plt.xlabel("X Axis Label\n(Two Lines)")
plt.ylabel("Y Axis Label\n(Two Lines)")
plt.show()
7. Mathematical Expressions in Labels
You can add mathematical expressions in labels using LaTeX syntax by wrapping the expression in dollar signs ($).
plt.title(r"$\alpha + \beta$ Equation")
plt.xlabel(r"$x^2 + y^2 = z^2$")
plt.show()
In this example, r before the string tells Python it’s a raw string, and the content between dollar signs is LaTeX code.
8. Text Box
You can add a text box anywhere in the plot using plt.text() or plt.figtext():
plt.plot(x, y)
# Add text at coordinates (2, 30)
plt.text(2, 30, "Text Label", fontsize=12, color='blue')
# Add text box
plt.text(4, 25, 'Important Point', fontsize=10, bbox=dict(facecolor='yellow', alpha=0.5))
plt.show()
The bbox argument adds a background color to the text, which can be customized with facecolor, alpha (for transparency), and more.
9. Subplot Titles (Suptitle)
When creating multiple subplots, you can add a global title for the entire figure using plt.suptitle().
plt.subplot(2, 1, 1)
plt.plot(x, y)
plt.subplot(2, 1, 2)
plt.plot(x, [i*2 for i in y])
# Add a global title
plt.suptitle("Global Plot Title", fontsize=16)
plt.show()
10. Adjusting Label Position
You can adjust the position of labels using the labelpad argument:
plt.xlabel("X Axis", labelpad=20) # Increase space between label and axis
plt.ylabel("Y Axis", labelpad=20)
Summary of Labeling Functions
- Title:
plt.title("Title") - X-Axis Label:
plt.xlabel("X Label") - Y-Axis Label:
plt.ylabel("Y Label") - Ticks and Custom Tick Labels:
plt.xticks([ticks], [labels]),plt.yticks([ticks], [labels]) - Legend:
plt.legend() - Annotations:
plt.annotate("Text", xy=(x, y), xytext=(xtext, ytext)) - Text Box:
plt.text(x, y, "Text") - Multiline Labels: Use
\nfor new lines in labels. - Mathematical Expressions: Use LaTeX syntax within
$...$for equations. - Global Title:
plt.suptitle("Global Title")
Conclusion
Labels in Matplotlib are critical for making your plots informative and easy to understand. With options to customize titles, axis labels, tick marks, legends, and annotations, you can ensure that your visualizations convey the necessary information effectively.