0
0
Matplotlibdata~5 mins

Legend outside the plot in Matplotlib - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Legend outside the plot
O(n)
Understanding Time Complexity

We want to understand how the time to draw a legend outside the plot changes as the number of legend items grows.

How does adding more items affect the drawing time?

Scenario Under Consideration

Analyze the time complexity of the following matplotlib code snippet.

import matplotlib.pyplot as plt

n = 10  # Define n before using it
fig, ax = plt.subplots()
for i in range(n):
    ax.plot([0, 1], [i, i], label=f'Line {i}')

ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))
plt.show()

This code plots n lines and places the legend outside the plot on the right side.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Loop adding n lines and legend entries.
  • How many times: The loop runs n times, once per line and legend item.
How Execution Grows With Input

As the number of lines n increases, the number of legend entries also increases, so the drawing work grows.

Input Size (n)Approx. Operations
10About 10 legend items drawn
100About 100 legend items drawn
1000About 1000 legend items drawn

Pattern observation: The work grows roughly in direct proportion to n.

Final Time Complexity

Time Complexity: O(n)

This means the time to draw the legend grows linearly as you add more items.

Common Mistake

[X] Wrong: "Adding the legend outside the plot does not affect drawing time much."

[OK] Correct: Even outside the plot, each legend item must be drawn, so more items mean more work.

Interview Connect

Understanding how drawing elements scale helps you write efficient plotting code and explain performance in data visualization tasks.

Self-Check

"What if we used fewer legend items by grouping lines? How would the time complexity change?"