Secondary axes in Matplotlib - Time & Space Complexity
We want to understand how the time to create a plot with secondary axes changes as the data size grows.
How does adding a secondary axis affect the work matplotlib does?
Analyze the time complexity of the following code snippet.
import matplotlib.pyplot as plt
import numpy as np
n = 100 # example size
x = np.linspace(0, 10, n)
y1 = np.sin(x)
y2 = np.log(x + 1)
fig, ax1 = plt.subplots()
ax1.plot(x, y1, 'b-')
ax2 = ax1.twinx()
ax2.plot(x, y2, 'r--')
This code creates a plot with two y-axes sharing the same x-axis, plotting two different data series.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Plotting each data point for both y1 and y2 arrays.
- How many times: Each plotting call processes all n points once.
As the number of points n increases, matplotlib must draw more points for both lines.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 20 operations (10 points per line x 2 lines) |
| 100 | About 200 operations |
| 1000 | About 2000 operations |
Pattern observation: The work grows roughly twice as fast as n because two lines are plotted, but still grows linearly with n.
Time Complexity: O(n)
This means the time to draw the plot grows directly in proportion to the number of data points.
[X] Wrong: "Adding a secondary axis doubles the time complexity to O(n²)."
[OK] Correct: The secondary axis adds another line to plot, but each line is drawn once over n points, so the time grows linearly, not quadratically.
Understanding how plotting scales with data size helps you explain performance in data visualization tasks clearly and confidently.
"What if we added a loop to plot m different lines on the same axes? How would the time complexity change?"