Viewing angle control in Matplotlib - Time & Space Complexity
We want to understand how changing the viewing angle in a 3D plot affects the time it takes to draw the plot.
How does the cost grow when we adjust the angle repeatedly?
Analyze the time complexity of the following code snippet.
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
X, Y = np.meshgrid(np.arange(0, 10), np.arange(0, 10))
Z = np.sin(X) + np.cos(Y)
ax.plot_surface(X, Y, Z)
ax.view_init(elev=30, azim=45)
plt.show()
This code creates a 3D surface plot and sets the viewing angle with elevation and azimuth.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Drawing the 3D surface with all points in the meshgrid.
- How many times: Once per plot, but if the angle changes repeatedly, the drawing repeats each time.
As the number of points in the grid increases, the drawing work grows because more points must be rendered.
| Input Size (n x n grid) | Approx. Operations |
|---|---|
| 10 x 10 | 100 points drawn |
| 100 x 100 | 10,000 points drawn |
| 1000 x 1000 | 1,000,000 points drawn |
Pattern observation: The drawing cost grows roughly with the square of the grid size.
Time Complexity: O(n^2)
This means the time to draw the plot grows with the square of the number of points in the grid.
[X] Wrong: "Changing the viewing angle is free and does not affect drawing time."
[OK] Correct: Changing the angle causes the plot to redraw, which takes time proportional to the number of points.
Understanding how rendering time grows with data size and view changes helps you explain performance in data visualization tasks.
What if we changed the grid from a square (n x n) to a rectangular shape (n x m)? How would the time complexity change?