3

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.

4
  • 1
    I'm not sure I totally understand what you mean by 'highlight'. Do you mean you just want plot some points on top of some specified positions in the matrix? Commented Mar 31, 2013 at 17:04
  • at the moment they are all black, when i press a button it shows some of them in a different colour Commented Mar 31, 2013 at 18:22
  • I still don't understand what you're trying to do. How do you want to specify which elements to highlight? What do you mean by 'It doesn't matter what points are highlighted, just some points'? Do you always want to highlight the same elements in the matrix, or will they change? Commented Apr 1, 2013 at 11:43
  • edited it, I have a list of coordinates that I want highlighted Commented Apr 1, 2013 at 11:45

1 Answer 1

3

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Beautiful answer. For beginners: Just remove ",visible=False". Add line: "highlight(); show()"

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.