0
0
Matplotlibdata~5 mins

Horizontal grouped bars in Matplotlib - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Horizontal grouped bars
O(n x g)
Understanding Time Complexity

We want to understand how the time to draw horizontal grouped bars changes as we add more groups or bars.

How does the drawing time grow when the data size grows?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

import matplotlib.pyplot as plt
import numpy as np

labels = ['A', 'B', 'C']
values1 = [5, 7, 3]
values2 = [6, 2, 4]

x = np.arange(len(labels))
width = 0.35

plt.barh(x - width/2, values1, height=width, label='Group 1')
plt.barh(x + width/2, values2, height=width, label='Group 2')

plt.yticks(x, labels)
plt.legend()
plt.show()

This code draws two horizontal bars side by side for each label, grouping them visually.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Drawing bars for each group and label combination.
  • How many times: For each label, bars are drawn for each group, so total bars = number of labels x number of groups.
How Execution Grows With Input

As the number of labels or groups increases, the number of bars to draw grows proportionally.

Input Size (labels x groups)Approx. Operations (bars drawn)
10 labels x 2 groups = 2020 bars
100 labels x 2 groups = 200200 bars
1000 labels x 2 groups = 20002000 bars

Pattern observation: The drawing time grows linearly with the total number of bars.

Final Time Complexity

Time Complexity: O(n * g)

This means the time grows in direct proportion to the number of labels (n) times the number of groups (g).

Common Mistake

[X] Wrong: "Adding more groups does not affect drawing time much because bars are drawn together."

[OK] Correct: Each group adds a full set of bars for every label, so total bars increase and so does drawing time.

Interview Connect

Understanding how drawing time scales helps you explain performance when visualizing large datasets with grouped bars.

Self-Check

What if we changed from grouped bars to stacked bars? How would the time complexity change?