Legend placement and styling in Matplotlib - Time & Space Complexity
When we add and style a legend in a matplotlib plot, the computer does extra work to place and draw it.
We want to know how this extra work grows when the legend has more items or styles.
Analyze the time complexity of the following code snippet.
import matplotlib.pyplot as plt
n = 10 # Define n before using it
labels = [f'Line {i}' for i in range(1, n+1)]
for i in range(n):
plt.plot([0, 1], [i, i], label=labels[i])
plt.legend(loc='upper right', fontsize=10, frameon=True)
plt.show()
This code plots n lines and adds a legend with n labels, styling it with font size and a frame.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through n lines to plot and label each one.
- How many times: The loop runs n times, once per line and label.
As the number of lines n grows, the work to plot and label each line grows roughly the same.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 plotting and labeling steps |
| 100 | About 100 plotting and labeling steps |
| 1000 | About 1000 plotting and labeling steps |
Pattern observation: The work grows directly with the number of legend items.
Time Complexity: O(n)
This means the time to place and style the legend grows linearly with the number of items.
[X] Wrong: "Adding a legend is always a fixed cost no matter how many items it has."
[OK] Correct: Each legend item adds work because it must be drawn and positioned, so more items mean more time.
Understanding how adding features like legends affects performance helps you write efficient data visualizations in real projects.
"What if we added multiple legends or complex custom styles? How would the time complexity change?"