Dual y-axis for different scales in Matplotlib - Time & Space Complexity
When we create a plot with two y-axes in matplotlib, we want to understand how the time to draw the plot changes as we add more data points.
We ask: How does the plotting time grow when the data size grows?
Analyze the time complexity of the following matplotlib code snippet.
import matplotlib.pyplot as plt
n = 10 # Example value for n
x = range(n)
y1 = [i for i in x]
y2 = [i**2 for i in x]
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.plot(x, y1, 'g-')
ax2.plot(x, y2, 'b-')
plt.show()
This code plots two lines sharing the same x-axis but with different y-axes scales.
- Primary operation: Plotting each data point for both y1 and y2 lines.
- How many times: Each line plots n points, so 2 * n plotting operations.
As the number of data points n increases, the number of plotting operations grows roughly in direct proportion.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 20 (2 lines * 10 points) |
| 100 | 200 (2 lines * 100 points) |
| 1000 | 2000 (2 lines * 1000 points) |
Pattern observation: The operations grow linearly with the number of points.
Time Complexity: O(n)
This means the time to plot grows directly in proportion to the number of data points.
[X] Wrong: "Adding a second y-axis doubles the time complexity to O(n^2)."
[OK] Correct: The second y-axis adds another line to plot, but plotting each point is still done once per point, so the growth stays linear, not squared.
Understanding how plotting time grows helps you explain performance when visualizing large datasets, a useful skill in data science and analysis.
What if we added a third y-axis with another line? How would the time complexity change?