0
0
Matplotlibdata~5 mins

Horizontal bar chart with plt.barh in Matplotlib - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Horizontal bar chart with plt.barh
O(n)
Understanding Time Complexity

We want to understand how the time to draw a horizontal bar chart changes as we add more bars.

How does the work grow when the number of bars increases?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

import matplotlib.pyplot as plt

labels = ['A', 'B', 'C', 'D', 'E']
values = [5, 7, 3, 8, 4]

plt.barh(labels, values)
plt.show()

This code draws a horizontal bar chart with 5 bars labeled A to E with given values.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Drawing each bar on the chart.
  • How many times: Once for each label and value pair (here 5 times).
How Execution Grows With Input

As the number of bars increases, the drawing work grows linearly.

Input Size (n)Approx. Operations
1010 drawing steps
100100 drawing steps
10001000 drawing steps

Pattern observation: Doubling the bars doubles the drawing work.

Final Time Complexity

Time Complexity: O(n)

This means the time to draw the chart grows directly with the number of bars.

Common Mistake

[X] Wrong: "Drawing a bar chart takes the same time no matter how many bars there are."

[OK] Correct: Each bar needs to be drawn separately, so more bars mean more work.

Interview Connect

Understanding how drawing time grows helps you explain performance when visualizing data with many points.

Self-Check

What if we added nested loops to draw grouped bars? How would the time complexity change?