Rcparams for global defaults in Matplotlib - Time & Space Complexity
We want to understand how changing global settings in matplotlib affects the time it takes to create plots.
Specifically, how does setting global defaults with rcParams impact performance as we make more plots?
Analyze the time complexity of the following code snippet.
import matplotlib.pyplot as plt
plt.rcParams['lines.linewidth'] = 2
plt.rcParams['axes.titlesize'] = 'large'
for i in range(n):
plt.plot([1, 2, 3], [i, i+1, i+2])
plt.title(f'Plot {i}')
plt.show()
This code sets global style defaults once, then creates and shows n plots using those defaults.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Loop creating and displaying n plots.
- How many times: n times, once per plot.
Each plot creation and display takes roughly the same time, so total time grows as we add more plots.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 plot creations and displays |
| 100 | 100 plot creations and displays |
| 1000 | 1000 plot creations and displays |
Pattern observation: The total work grows linearly as the number of plots increases.
Time Complexity: O(n)
This means the time to run the code grows in direct proportion to the number of plots created.
[X] Wrong: "Setting rcParams inside the loop will not affect performance."
[OK] Correct: Changing rcParams inside the loop repeats the global setting step each time, adding extra work and slowing down the process.
Understanding how global settings affect repeated operations helps you write efficient plotting code and shows you can think about performance in real tasks.
"What if we set rcParams inside the loop before each plot? How would the time complexity change?"