3D bar charts in Matplotlib - Time & Space Complexity
When creating 3D bar charts, we want to know how the time to draw the chart changes as we add more bars.
How does adding more bars affect the work matplotlib does?
Analyze the time complexity of the following code snippet.
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x, y = np.arange(5), np.arange(5)
xpos, ypos = np.meshgrid(x, y)
xpos = xpos.flatten()
ypos = ypos.flatten()
zpos = np.zeros_like(xpos)
dx = dy = dz = np.ones_like(zpos)
ax.bar3d(xpos, ypos, zpos, dx, dy, dz)
plt.show()
This code creates a 3D bar chart with 25 bars arranged in a grid.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Drawing each bar in the 3D space.
- How many times: Once for each bar, here 25 times (5x5 grid).
Each new bar adds a fixed amount of work to draw it.
| Input Size (n bars) | Approx. Operations |
|---|---|
| 10 | 10 drawing steps |
| 100 | 100 drawing steps |
| 1000 | 1000 drawing steps |
Pattern observation: The work grows directly with the number of bars.
Time Complexity: O(n)
This means the time to draw the chart grows in a straight line as you add more bars.
[X] Wrong: "Adding more bars won't affect drawing time much because they are all drawn together."
[OK] Correct: Each bar requires separate drawing steps, so more bars mean more work and longer drawing time.
Understanding how drawing time grows helps you explain performance when visualizing large datasets with 3D charts.
What if we changed the bars to be stacked instead of side-by-side? How would the time complexity change?