Color mapping with colorbar in Matplotlib - Time & Space Complexity
We want to understand how the time needed to create a color map with a colorbar changes as we increase the data size.
How does the work grow when we add more points to the plot?
Analyze the time complexity of the following code snippet.
import matplotlib.pyplot as plt
import numpy as np
n = 1000
x = np.random.rand(n)
y = np.random.rand(n)
z = np.random.rand(n)
plt.scatter(x, y, c=z, cmap='viridis')
plt.colorbar()
plt.show()
This code creates a scatter plot of n points colored by values in z, then adds a colorbar to explain the colors.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Plotting each of the n points with a color based on z.
- How many times: Once for each of the n points.
As we add more points, the plotting work grows roughly in direct proportion to the number of points.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 plotting operations |
| 100 | 100 plotting operations |
| 1000 | 1000 plotting operations |
Pattern observation: Doubling the points roughly doubles the work needed to plot and color them.
Time Complexity: O(n)
This means the time to create the colored scatter plot with colorbar grows linearly with the number of points.
[X] Wrong: "Adding a colorbar makes the time grow much faster than the points plotted."
[OK] Correct: The colorbar is created once and does not depend on the number of points, so it adds a small fixed cost, not a growing one.
Understanding how plotting time grows with data size helps you explain performance in data visualization tasks clearly and confidently.
What if we changed the scatter plot to a heatmap with a fixed grid size? How would the time complexity change?