pythonpython-3.xmatplotlibheatmapastropy

How to encircle some pixels on a heat map with a continuous line using Python?


I am using plt.imshow() to plot values on a grid (CCD data in my case). An example plot:

enter image description here

I need to indicate a barrier on it, to show which pixels I care about. This is similar to what I need:

enter image description here

I know how to add squares to an image, gridlines to an image, but this knowledge doesn't solve the issuue, nor adding single squares to the pic, which is also within my abilities. I need a line which encircles an area on the grid (and this line will always need to go between pixels, not across them so this might make it simpler a bit).

How can I do this?


Iury Sousa has provided a nice work-around to the question above. However, it is not strictly circling the area with a line (rather plotting a mask to the picture and then covering most of it with the picture again), and it fails when I try to encircle overlapping group of pixels. ImportanceOfBeingErnest suggested in the comments that I should simply use the plt.plot sample. Using Iury Sousa's example as a starting point lets have:

X,Y = np.meshgrid(range(30),range(30))
Z = np.sin(X)+np.sin(Y)
selected1 = Z>1.5

Now selected1 is an array of boolean arrays, and we would like to circle only those pixels which have corresponding Z value above 1.5. We also would like to circle selected2, which contains True values for pixels with value above 0.2 and below 1.8:

upperlim_selected2 = Z<1.8
selected2 = upperlim_selected2>0.2

Iury Sousa's great work-around doesn't work for this case. plt.plot would, in my opinion. What is an efficient way to achieve the circling of selected1 and selected2, either using plt.plot or another method?


Solution

  • Similar to the answer in Can matplotlib contours match pixel edges? you can create a grid with a higher resolution and draw a contour plot.

    import numpy as np
    import matplotlib.pyplot as plt
    
    X,Y = np.meshgrid(range(30),range(30))
    Z = np.sin(X)+np.sin(Y)
    
    resolution = 25
    
    f = lambda x,y: Z[int(y),int(x) ]
    g = np.vectorize(f)
    
    x = np.linspace(0,Z.shape[1], Z.shape[1]*resolution)
    y = np.linspace(0,Z.shape[0], Z.shape[0]*resolution)
    X2, Y2= np.meshgrid(x[:-1],y[:-1])
    Z2 = g(X2,Y2)
    
    
    plt.pcolormesh(X,Y, Z)
    plt.contour(X2,Y2,Z2, [1.5], colors='r', linewidths=[1])
    
    plt.show()
    

    enter image description here