Line colors and width in Matplotlib - Time & Space Complexity
We want to understand how the time to draw lines changes when we change their colors and widths in matplotlib.
How does the drawing time grow as we add more lines with different colors and widths?
Analyze the time complexity of the following code snippet.
import matplotlib.pyplot as plt
x = range(1000)
for i in range(100):
plt.plot(x, [j + i for j in x], color=f'C{i%10}', linewidth=0.5 + i*0.05)
plt.show()
This code draws 100 lines, each with a different color and width, on the same plot.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The loop that draws each line with specific color and width.
- How many times: 100 times, once per line.
As the number of lines increases, the drawing time grows roughly in direct proportion.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 line draws |
| 100 | 100 line draws |
| 1000 | 1000 line draws |
Pattern observation: Doubling the number of lines roughly doubles the work done.
Time Complexity: O(n)
This means the time to draw lines grows linearly with the number of lines.
[X] Wrong: "Changing line colors or widths makes the drawing time grow faster than the number of lines."
[OK] Correct: The color and width settings are simple properties applied per line and do not add extra loops or nested work, so they do not increase the growth rate beyond linear.
Understanding how drawing operations scale helps you reason about performance in data visualization tasks, a useful skill in many data science projects.
What if we added nested loops to draw multiple points per line with different styles? How would the time complexity change?