Polar axes in Matplotlib - Time & Space Complexity
We want to understand how the time to draw a polar plot changes as we add more data points.
How does the plotting time grow when the input size increases?
Analyze the time complexity of the following code snippet.
import matplotlib.pyplot as plt
import numpy as np
n = 100 # Define n
# Create data
theta = np.linspace(0, 2 * np.pi, n)
r = np.abs(np.sin(5 * theta))
# Create polar plot
fig, ax = plt.subplots(subplot_kw={'projection': 'polar'})
ax.plot(theta, r)
plt.show()
This code creates a polar plot with n points, plotting radius r against angle theta.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Calculating and plotting
npoints on the polar axes. - How many times: Once for each of the
npoints in the arraysthetaandr.
As we increase the number of points, the time to compute and draw grows roughly in direct proportion.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 operations |
| 100 | 100 operations |
| 1000 | 1000 operations |
Pattern observation: Doubling the points roughly doubles the work needed to plot.
Time Complexity: O(n)
This means the time to create the polar plot grows linearly with the number of points.
[X] Wrong: "Adding more points won't affect the plotting time much because it's just one plot."
[OK] Correct: Each point requires calculation and drawing, so more points mean more work and longer plotting time.
Understanding how plotting time grows helps you write efficient code and explain performance clearly in real projects.
What if we changed the plot to scatter points instead of a line plot? How would the time complexity change?