Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Highlight certain points on a matplotlib matrix

I have created a matrix in matplotlib using imshow(). When I press a button I want certain plotted points on the matrix to be highlighted. I have a set of coordinates in a list that I want selecting. My matrix is also a binary matrix.

like image 310
John Smith Avatar asked Aug 01 '26 05:08

John Smith


1 Answers

If I understand what you're asking for correctly, I would do this is by imshowing an RGBA overlay on top of the matrix, with the alpha channel set to zero except at the points that you want to 'highlight'. You can then toggle the visibility of the overlay to toggle the highlighting on and off.

from matplotlib.pyplot import *
import numpy as np

def highlight():
    m = np.random.randn(10,10)
    highlight = m < 0

    # RGBA overlay matrix
    overlay = np.zeros((10,10,4))

    # we set the red channel to 1
    overlay[...,0] = 1.

    # and we set the alpha to our boolean matrix 'highlight' so that it is
    # transparent except for highlighted pixels
    overlay[...,3] = highlight

    fig,ax = subplots(1,1,num='Press "h" to highlight pixels < 0')

    im = ax.imshow(m,interpolation='nearest',cmap=cm.gray)
    colorbar(im)
    ax.hold(True)
    h = ax.imshow(overlay,interpolation='nearest',visible=False)

    def toggle_highlight(event):
        # if the user pressed h, toggle the visibility of the overlay
        if event.key == 'h':
            h.set_visible(not h.get_visible())
            fig.canvas.draw()

    # connect key events to the 'toggle_highlight' callback
    fig.canvas.mpl_connect('key_release_event',toggle_highlight)
like image 54
ali_m Avatar answered Aug 03 '26 18:08

ali_m



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!