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.
-
1I'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?ali_m– ali_m2013-03-31 17:04:04 +00:00Commented 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 colourJohn Smith– John Smith2013-03-31 18:22:33 +00:00Commented 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?ali_m– ali_m2013-04-01 11:43:26 +00:00Commented Apr 1, 2013 at 11:43
-
edited it, I have a list of coordinates that I want highlightedJohn Smith– John Smith2013-04-01 11:45:31 +00:00Commented Apr 1, 2013 at 11:45
Add a comment
|
1 Answer
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)
1 Comment
roadrunner66
Beautiful answer. For beginners: Just remove ",visible=False". Add line: "highlight(); show()"