What is the correct way to replace matplotlib tick labels with computed values?

We can use ax.loglog(x, y) and set_major_formatter() methods to replace matplotlib tick labels with computed values. This technique is particularly useful when working with logarithmic scales or when you need custom formatting for your axis labels.

Steps

  • Set the figure size and adjust the padding between and around the subplots.

  • Create a figure and a set of subplots.

  • Make a plot with log scaling on both the X and Y axis.

  • Set the formatter of the major ticker.

  • To display the figure, use show() method.

Example 1: Using LogFormatterExponent

Here's how to replace tick labels with exponential notation −

import numpy as np
from matplotlib import pyplot as plt, ticker

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

fig, ax = plt.subplots()

# Create logarithmic plot
x = np.logspace(0, 5)
y = x**2
ax.loglog(x, y)

# Format x-axis with exponential notation
ax.xaxis.set_major_formatter(ticker.LogFormatterExponent())

plt.title("Logarithmic Plot with Exponential Notation")
plt.show()

Example 2: Using Custom Formatter

You can also create a custom formatter for more control over tick labels −

import numpy as np
from matplotlib import pyplot as plt, ticker

fig, ax = plt.subplots(figsize=(8, 4))

# Sample data
x = np.linspace(0, 10, 100)
y = np.exp(x/5)

ax.semilogy(x, y)

# Custom formatter function
def custom_formatter(x, pos):
    return f'{x:.1f}s'

# Apply custom formatter to x-axis
ax.xaxis.set_major_formatter(ticker.FuncFormatter(custom_formatter))

plt.title("Semi-log Plot with Custom Tick Labels")
plt.xlabel("Time")
plt.ylabel("Value")
plt.show()

Example 3: Using FixedFormatter for Specific Labels

For completely custom labels at specific positions −

import numpy as np
from matplotlib import pyplot as plt, ticker

fig, ax = plt.subplots(figsize=(8, 4))

# Sample data
x = np.arange(5)
y = [10, 25, 40, 30, 15]

ax.bar(x, y)

# Set custom tick labels
custom_labels = ['Jan', 'Feb', 'Mar', 'Apr', 'May']
ax.xaxis.set_major_formatter(ticker.FixedFormatter(custom_labels))
ax.xaxis.set_major_locator(ticker.FixedLocator(x))

plt.title("Bar Chart with Custom Month Labels")
plt.ylabel("Sales")
plt.show()

Common Formatter Types

Formatter Use Case Example Output
LogFormatterExponent Logarithmic scales 103, 104
FuncFormatter Custom function Any custom format
FixedFormatter Specific labels Text labels
PercentFormatter Percentage values 25%, 50%, 75%

Conclusion

Use set_major_formatter() with appropriate formatter classes to customize tick labels. Choose LogFormatterExponent for logarithmic plots, FuncFormatter for custom functions, or FixedFormatter for specific text labels.

Updated on: 2026-03-26T00:26:48+05:30

393 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements