So I want something like a 2D histogram or heatmap. I have data as a grid following the format (x, y, value) like [(0, 0, 5), (0, 1, 7), (0, 2, 8), ...]. I just want to plot a grid where each square has a colour corresponding to value, and the position of each grid point is given by the x, y coordinates.
Asked
Active
Viewed 155 times
0
-
you should have a look at https://stackoverflow.com/questions/14120222 – Olivier Gauthé Feb 09 '23 at 14:42
1 Answers
1
The linked question is interesting, but if I understand the OP correctly, in this case the data do form a full rectangular grid, so there is no need to interpolate any values. Assuming the data tuples are sorted according to the x
and y
values as in the example, you can easily reencode them as a 2-dimensional array, which is more common for image data and can be passed to plt.imshow()
.
import numpy as np
import matplotlib.pyplot as plt
grid = [(0, 0, 5), (0, 1, 7), (0, 2, 8),
(1, 0, 6), (1, 1, 8), (1, 2, 8),
(2, 0, 7), (2, 1, 9), (2, 2, 9),
(3, 0, 8), (3, 1, 8), (3, 2, 9)]
x, y, z = zip(*grid)
a = np.array(z).reshape((max(x) + 1, max(y) + 1))
plt.imshow(a, cmap='Blues')

Arne
- 9,990
- 2
- 18
- 28
-
1Or with seaborn: `sns.heatmap(data=pd.DataFrame(grid).pivot(0, 1, 2), annot=True)` – JohanC Feb 09 '23 at 15:59