0
0
Matplotlibdata~5 mins

Secondary axes in Matplotlib - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Secondary axes
O(n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

As the number of points n increases, matplotlib must draw more points for both lines.

Input Size (n)Approx. Operations
10About 20 operations (10 points per line x 2 lines)
100About 200 operations
1000About 2000 operations

Pattern observation: The work grows roughly twice as fast as n because two lines are plotted, but still grows linearly with n.

Final Time Complexity

Time Complexity: O(n)

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

Common Mistake

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

Interview Connect

Understanding how plotting scales with data size helps you explain performance in data visualization tasks clearly and confidently.

Self-Check

"What if we added a loop to plot m different lines on the same axes? How would the time complexity change?"