0
0
Matplotlibdata~5 mins

Dual y-axis for different scales in Matplotlib - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Dual y-axis for different scales
O(n)
Understanding Time 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?

Scenario Under Consideration

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.

Identify Repeating Operations
  • 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.
How Execution Grows With Input

As the number of data points n increases, the number of plotting operations grows roughly in direct proportion.

Input Size (n)Approx. Operations
1020 (2 lines * 10 points)
100200 (2 lines * 100 points)
10002000 (2 lines * 1000 points)

Pattern observation: The operations grow linearly with the number of points.

Final Time Complexity

Time Complexity: O(n)

This means the time to plot grows directly in proportion to the number of data points.

Common Mistake

[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.

Interview Connect

Understanding how plotting time grows helps you explain performance when visualizing large datasets, a useful skill in data science and analysis.

Self-Check

What if we added a third y-axis with another line? How would the time complexity change?