Heatmap with plt.pcolormesh in Matplotlib - Time & Space Complexity
When creating a heatmap using plt.pcolormesh, it is important to understand how the time to draw the heatmap changes as the data size grows.
We want to know how the drawing time increases when we have more rows and columns in our data.
Analyze the time complexity of the following code snippet.
import matplotlib.pyplot as plt
import numpy as np
# Create a 2D array of size n x n
n = 100
data = np.random.rand(n, n)
plt.pcolormesh(data)
plt.show()
This code creates a heatmap of a square 2D array with random values using plt.pcolormesh.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Drawing colored cells for each element in the 2D array.
- How many times: Once for each of the n x n elements, so n squared times.
As the size of the data (n) grows, the number of colored cells to draw grows with the square of n.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 100 |
| 100 | 10,000 |
| 1000 | 1,000,000 |
Pattern observation: Doubling the size of one dimension multiplies the total work by four, because the area grows with n squared.
Time Complexity: O(n²)
This means the time to draw the heatmap grows roughly with the square of the data size, as each cell must be processed.
[X] Wrong: "The drawing time grows linearly with the number of rows or columns."
[OK] Correct: Because the heatmap has both rows and columns, the total number of cells grows with the product of rows and columns, not just one dimension.
Understanding how visualization time grows with data size helps you make smart choices about data display and performance in real projects.
"What if we used plt.imshow instead of plt.pcolormesh? How would the time complexity change?"