Figure-level methods vs axes-level in Matplotlib - Performance Comparison
When using matplotlib, we can draw plots using figure-level or axes-level methods. Understanding how the time to draw grows with data size helps us choose the right method.
We want to know: how does the time to create plots change as we add more data points?
Analyze the time complexity of the following matplotlib code snippets.
import matplotlib.pyplot as plt
import numpy as np
n = 100 # example size
x = np.linspace(0, 10, n)
y = np.sin(x)
# Figure-level method
plt.plot(x, y)
# Axes-level method
fig, ax = plt.subplots()
ax.plot(x, y)
This code plots a line chart with n data points using two approaches: figure-level and axes-level.
Look for repeated work done as data size grows.
- Primary operation: Drawing each data point on the plot.
- How many times: Once per data point, so n times.
As we add more points, the drawing work grows roughly in a straight line.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 drawing steps |
| 100 | 100 drawing steps |
| 1000 | 1000 drawing steps |
Pattern observation: Doubling data roughly doubles the work needed to draw.
Time Complexity: O(n)
This means the time to draw grows linearly with the number of data points.
[X] Wrong: "Figure-level methods are always slower because they handle more stuff."
[OK] Correct: Both figure-level and axes-level methods spend most time drawing data points, so their time grows similarly with data size.
Knowing how plotting time grows helps you explain choices in data visualization tasks clearly and confidently.
What if we added multiple lines to the same axes? How would the time complexity change?