Home > front end >  Heatmap for given areas by coordinates
Heatmap for given areas by coordinates

Time:08-08

Let's say there is a 100*100 grid in the range of [0,1]. Each point in this grid with coordinates (x,y) has some value Z, where x and y can take any of the values {0.01, 0.02, 0.03, …, 1}. However, in the chart below, only points in certain areas matter (e.g. the rectangles in chart below).

I have a method F that when given a point with its coordinates tells me whether that point matters, I used a rectangle in the chart below just for demonstration - it’s not necessarily a rectangle. So I can calculate the centers of all the points for which I need the heatmap for - the rest should be white.

I was thinking maybe I can first build a 2D array of size 100*100 and populate it with the corresponding Z value for that coordinate, but then using the method F, set the Z for coordinates outside of those rectangles to some number (0, or -10000) that will result in white in the final heatmap, but couldn't quite make it happen.

Any help would be appreciated.

enter image description here

CodePudding user response:

If all you are trying to do is blank out some of the image, just set it to NaN:

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()
data = np.random.randn(100, 100)
x = np.arange(100)
y = np.arange(100)
X, Y = np.meshgrid(x,y)

data[((X**2   (Y-30)**2) > 25**2)
     & ~((X>20) & (X<83) & (Y>60) & (Y<85))] = np.NaN

ax.imshow(data)

Image with everything blanked out except a half circle and a rectangle

imshow has an extent argument that you can use to arbitrarily place images on the axes.

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()
ax.imshow(np.random.randn(4, 5), extent=(3, 8, 2, 6))
ax.imshow(np.random.randn(7, 3), extent=(1, 2.7, 6.3, 9.8))
ax.set_xlim(0, 10)
ax.set_ylim(0, 10)
plt.show()

Two heat-maps on the same axes

You can do the same thing with pcolormesh.

  • Related