Percentage labels in Matplotlib - Time & Space Complexity
We want to understand how the time needed to add percentage labels in a matplotlib chart changes as the data size grows.
How does the work increase when we add more slices to a pie chart with percentage labels?
Analyze the time complexity of the following code snippet.
import matplotlib.pyplot as plt
sizes = [10, 20, 30, 40]
labels = ['A', 'B', 'C', 'D']
plt.pie(sizes, labels=labels, autopct='%1.1f%%')
plt.show()
This code creates a pie chart with four slices and shows percentage labels on each slice.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Drawing each slice and calculating its percentage label.
- How many times: Once for each slice in the data list.
As the number of slices increases, the work to draw and label each slice grows directly with it.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 slice drawings and 10 percentage calculations |
| 100 | 100 slice drawings and 100 percentage calculations |
| 1000 | 1000 slice drawings and 1000 percentage calculations |
Pattern observation: The work grows in a straight line as the number of slices increases.
Time Complexity: O(n)
This means the time to add percentage labels grows directly with the number of slices.
[X] Wrong: "Adding percentage labels takes the same time no matter how many slices there are."
[OK] Correct: Each slice needs its own label calculated and drawn, so more slices mean more work.
Understanding how labeling scales helps you explain performance when visualizing larger datasets clearly and confidently.
"What if we added custom labels with complex formatting instead of simple percentages? How would the time complexity change?"