3D surface plots in Matplotlib - Time & Space Complexity
When creating 3D surface plots, the time it takes depends on how many points we draw. We want to understand how the drawing time grows as we add more points.
How does the number of points affect the time to create the plot?
Analyze the time complexity of the following code snippet.
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
n = 50 # Example value for n
x = np.linspace(-5, 5, n)
y = np.linspace(-5, 5, n)
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_surface(X, Y, Z)
plt.show()
This code creates a 3D surface plot using a grid of points sized by n. It calculates values and draws the surface.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Calculating values for each point on an
nbyngrid and drawing them. - How many times: The calculation and plotting happen for every one of the
n * npoints.
As n grows, the number of points grows by the square of n. So the work grows quickly.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 100 (10 x 10) |
| 100 | 10,000 (100 x 100) |
| 1000 | 1,000,000 (1000 x 1000) |
Pattern observation: Doubling n makes the work about four times bigger because we have a grid of points.
Time Complexity: O(n2)
This means the time to create the 3D surface plot grows roughly with the square of the grid size.
[X] Wrong: "Increasing the grid size n only makes the plot take a little longer, like just doubling the time."
[OK] Correct: Because the grid is two-dimensional, increasing n means many more points (n times n), so the time grows much faster than just doubling.
Understanding how plotting time grows with data size helps you explain performance in data visualization tasks. This skill shows you can think about efficiency even when working with graphics.
"What if we used a 1D line plot instead of a 3D surface plot? How would the time complexity change?"