Bar charts in Data Analysis Python - Time & Space Complexity
When we create bar charts from data, we want to know how long it takes as the data grows.
We ask: How does the time to draw bars change when we have more data points?
Analyze the time complexity of the following code snippet.
import matplotlib.pyplot as plt
def draw_bar_chart(data):
labels = list(data.keys())
values = list(data.values())
plt.bar(labels, values)
plt.show()
This code draws a bar chart using labels and values from a data dictionary.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Drawing one bar for each data point.
- How many times: Once for each item in the data (n times).
As the number of data points grows, the number of bars to draw grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 bars drawn |
| 100 | 100 bars drawn |
| 1000 | 1000 bars drawn |
Pattern observation: The work grows directly with the number of data points.
Time Complexity: O(n)
This means the time to draw the bar chart grows linearly with the number of bars.
[X] Wrong: "Drawing a bar chart always takes the same time no matter how many bars there are."
[OK] Correct: Each bar needs to be drawn separately, so more bars mean more work and more time.
Understanding how drawing charts scales helps you explain performance when working with data visualizations in real projects.
"What if we added a loop inside the drawing function to draw multiple charts for each data point? How would the time complexity change?"