Custom tick formatters in Matplotlib - Time & Space Complexity
When we use custom tick formatters in matplotlib, we want to know how the time to draw the plot changes as we add more ticks.
We ask: How does the work grow when the number of ticks increases?
Analyze the time complexity of the following code snippet.
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
fig, ax = plt.subplots()
ax.plot(range(100))
ax.xaxis.set_major_formatter(ticker.FuncFormatter(lambda x, _: f'{x:.1f} units'))
plt.show()
This code plots 100 points and sets a custom formatter to change how x-axis ticks are shown.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The formatter function is called once for each tick on the axis.
- How many times: Equal to the number of ticks displayed on the axis.
As the number of ticks increases, the formatter function runs more times, so the total work grows linearly.
| Input Size (number of ticks) | Approx. Operations (formatter calls) |
|---|---|
| 10 | 10 |
| 100 | 100 |
| 1000 | 1000 |
Pattern observation: Doubling the number of ticks roughly doubles the number of formatter calls.
Time Complexity: O(n)
This means the time to format ticks grows directly in proportion to the number of ticks.
[X] Wrong: "The formatter runs only once, so time does not depend on tick count."
[OK] Correct: The formatter is called for each tick label, so more ticks mean more calls and more time.
Understanding how custom formatting affects performance helps you write efficient plots and shows you can think about code cost in real projects.
"What if the formatter function did a complex calculation for each tick? How would that affect the time complexity?"