How to Set xlabel and ylabel in Matplotlib: Simple Guide
To set the x-axis label in Matplotlib, use
plt.xlabel('label'). For the y-axis label, use plt.ylabel('label'). These functions add descriptive text to the axes of your plot.Syntax
Use plt.xlabel() to set the label for the x-axis and plt.ylabel() for the y-axis. Both functions take a string argument that is the label text.
plt.xlabel('text'): sets the label of the x-axis.plt.ylabel('text'): sets the label of the y-axis.
python
plt.xlabel('X Axis Label') plt.ylabel('Y Axis Label')
Example
This example shows how to create a simple line plot and add labels to the x and y axes using plt.xlabel() and plt.ylabel().
python
import matplotlib.pyplot as plt x = [1, 2, 3, 4, 5] y = [10, 20, 25, 30, 40] plt.plot(x, y) plt.xlabel('Time (seconds)') plt.ylabel('Distance (meters)') plt.title('Distance over Time') plt.show()
Output
A line plot with x-axis labeled 'Time (seconds)' and y-axis labeled 'Distance (meters)', titled 'Distance over Time'.
Common Pitfalls
Common mistakes when setting axis labels include:
- Forgetting to call
plt.xlabel()orplt.ylabel()beforeplt.show(), so labels do not appear. - Passing non-string values as labels, which can cause errors.
- Confusing axis labels with titles; use
plt.title()for the plot title.
python
import matplotlib.pyplot as plt x = [1, 2, 3] y = [4, 5, 6] plt.plot(x, y) # Wrong: labels after plt.show() - labels won't show plt.show() plt.xlabel('X Label') plt.ylabel('Y Label') # Correct way: plt.plot(x, y) plt.xlabel('X Label') plt.ylabel('Y Label') plt.show()
Quick Reference
Summary tips for setting axis labels in Matplotlib:
- Use
plt.xlabel('text')for x-axis label. - Use
plt.ylabel('text')for y-axis label. - Call these before
plt.show(). - Labels must be strings.
- Use
plt.title('text')for the plot title.
Key Takeaways
Use plt.xlabel('text') and plt.ylabel('text') to set axis labels in Matplotlib.
Always call label functions before plt.show() to see the labels on the plot.
Labels must be strings describing the axis clearly.
Use plt.title() separately for the plot title, not axis labels.
Setting clear labels helps make your plots easier to understand.