Lollipop charts in Matplotlib - Time & Space Complexity
When creating lollipop charts with matplotlib, it is important to understand how the time to draw the chart changes as the data size grows.
We want to know how the number of points affects the time matplotlib takes to draw the lines and markers.
Analyze the time complexity of the following code snippet.
import matplotlib.pyplot as plt
n = 10 # Example value for n
x = range(n)
y = [value for value in range(n)]
plt.stem(x, y, basefmt=' ')
plt.show()
This code draws a lollipop chart with n points, where each point has a vertical line and a marker.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Drawing n vertical lines and n markers on the plot.
- How many times: Each line and marker is drawn once for each of the n data points.
As the number of points n increases, the number of lines and markers to draw also increases proportionally.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 lines and 10 markers drawn |
| 100 | About 100 lines and 100 markers drawn |
| 1000 | About 1000 lines and 1000 markers drawn |
Pattern observation: The work grows directly with the number of points; doubling n roughly doubles the drawing work.
Time Complexity: O(n)
This means the time to draw the lollipop chart grows linearly with the number of data points.
[X] Wrong: "Drawing a lollipop chart takes the same time no matter how many points there are."
[OK] Correct: Each point adds a line and a marker, so more points mean more drawing work and longer time.
Understanding how plotting time grows with data size helps you write efficient visualizations and explain performance in real projects.
What if we added a loop to draw multiple lollipop charts one after another? How would the time complexity change?