Subplots for multiple charts in Data Analysis Python - Time & Space Complexity
When we create multiple charts using subplots, we want to know how the time to draw them grows as we add more charts.
We ask: How does the work increase when we add more charts to the subplot?
Analyze the time complexity of the following code snippet.
import matplotlib.pyplot as plt
import numpy as np
n = 5 # number of charts
x = np.linspace(0, 10, 1000)
fig, axs = plt.subplots(n, 1)
for i in range(n):
y = np.sin(x + i)
axs[i].plot(x, y)
plt.show()
This code creates 5 charts stacked vertically, each plotting a sine wave shifted by i.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Loop over
ncharts to plot data. - How many times: Exactly
ntimes, once per chart.
Each new chart adds a similar amount of work to draw the plot.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 times the work of one chart |
| 100 | 100 times the work of one chart |
| 1000 | 1000 times the work of one chart |
Pattern observation: The work grows directly with the number of charts added.
Time Complexity: O(n)
This means the time to create all charts grows in a straight line as you add more charts.
[X] Wrong: "Adding more charts won't increase time much because they are drawn together."
[OK] Correct: Each chart requires its own drawing steps, so more charts mean more work.
Understanding how work grows with more charts helps you explain performance when visualizing data in real projects.
What if we plotted all lines on a single chart instead of multiple subplots? How would the time complexity change?