Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to display all label values in Matplotlib?
To display all label values in Matplotlib, we can use set_xticklabels() and set_yticklabels() methods to customize axis tick labels with custom text, rotation, and spacing.
Basic Example
Here's how to set custom labels for both X and Y axes ?
import matplotlib.pyplot as plt plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True x = [1, 2, 3, 4] ax1 = plt.subplot() # Set tick positions ax1.set_xticks(x) ax1.set_yticks(x) # Set custom labels with rotation ax1.set_xticklabels(["one", "two", "three", "four"], rotation=45) ax1.set_yticklabels(["one", "two", "three", "four"], rotation=45) # Add padding and move ticks inside ax1.tick_params(axis="both", direction="in", pad=15) plt.show()
Step-by-Step Process
Create a list of numbers (x) to define tick positions
Get the axis using
subplot()to add a subplot to the current figureSet tick positions using
set_xticks()andset_yticks()methodsSet custom labels using
set_xticklabels()andset_yticklabels()with rotationUse
tick_params()to adjust spacing and tick directionDisplay the figure using
plt.show()
Displaying Labels with Data
Here's a more practical example with actual data plotting ?
import matplotlib.pyplot as plt
# Sample data
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May']
sales = [100, 150, 120, 180, 200]
plt.figure(figsize=(8, 5))
plt.plot(range(len(months)), sales, marker='o')
# Set all labels
plt.xticks(range(len(months)), months, rotation=45)
plt.xlabel('Months')
plt.ylabel('Sales ($)')
plt.title('Monthly Sales Data')
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
Key Parameters
| Parameter | Description | Example |
|---|---|---|
rotation |
Rotate labels by degrees | rotation=45 |
pad |
Distance between ticks and labels | pad=15 |
direction |
Tick direction (in/out/inout) | direction="in" |
Output
Conclusion
Use set_xticklabels() and set_yticklabels() to display custom labels on axes. The rotation parameter helps prevent overlapping labels, while tick_params() controls spacing and appearance.
