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 figure

  • Set tick positions using set_xticks() and set_yticks() methods

  • Set custom labels using set_xticklabels() and set_yticklabels() with rotation

  • Use tick_params() to adjust spacing and tick direction

  • Display 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

one two three four one two three four

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.

Updated on: 2026-03-25T19:48:58+05:30

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements