3D wireframe plots in Matplotlib - Time & Space Complexity
When creating 3D wireframe plots, we want to know how the time to draw the plot changes as we increase the data points.
We ask: How does the drawing time grow when we add more points to the 3D grid?
Analyze the time complexity of the following code snippet.
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
x = np.linspace(-5, 5, 50)
y = np.linspace(-5, 5, 50)
X, Y = np.meshgrid(x, y)
Z = np.sin(np.sqrt(X**2 + Y**2))
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_wireframe(X, Y, Z)
plt.show()
This code creates a 3D wireframe plot using a grid of 50 by 50 points.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Plotting lines between points on the 2D grid to form the wireframe.
- How many times: For a grid of size n by n, lines are drawn along rows and columns, roughly 2 * n * (n - 1) times.
As the grid size n increases, the number of lines to draw grows roughly with the square of n.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 180 lines |
| 100 | About 19,800 lines |
| 1000 | About 1,998,000 lines |
Pattern observation: Doubling n roughly quadruples the number of lines to draw, so the work grows fast as n grows.
Time Complexity: O(n^2)
This means the time to draw the wireframe grows roughly with the square of the grid size.
[X] Wrong: "The time to draw a 3D wireframe grows linearly with the number of points."
[OK] Correct: Because lines connect points in both directions (rows and columns), the number of lines grows with the square of the grid size, not just the number of points.
Understanding how plotting time grows helps you explain performance in data visualization tasks and shows you can think about efficiency beyond just writing code.
"What if we changed the grid to be rectangular with dimensions n by m instead of n by n? How would the time complexity change?"