0

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.

1 Answers1

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') 

example plot/heatmap

Arne
  • 9,990
  • 2
  • 18
  • 28