Reputation:
I'd like to know the color value of a point I click on when I use imshow() in matplotlib. Is there a way to find this information through the event handler in matplotlib (the same way as the x,y coordinates of your click are available)? If not, how would I find this information?
Specifically I'm thinking about a case like this:
imshow(np.random.rand(10,10)*255, interpolation='nearest')
Thanks! --Erin
Upvotes: 8
Views: 8070
Reputation: 435
You could try something like the below:
x, y = len(df.columns.values), len(df.index.values)
# subplot etc
# Set values for x/y ticks/labels
ax.set_xticks(np.linspace(0, x-1, x))
ax.set_xticklabels(ranges_df.columns)
ax.set_yticks(np.linspace(0, y-1, y))
ax.set_yticklabels(ranges_df.index)
for i, j in product(range(y), range(x)):
ax.text(j, i, '{0:.0f}'.format(ranges_df.iloc[i, j]),
size='small', ha='center', va='center')
Upvotes: 0
Reputation: 311
If by 'color value' you mean the value of the array at a clicked point on a graph, then this is useful.
from matplotlib import pyplot as plt
import numpy as np
class collect_points():
omega = []
def __init__(self,array):
self.array = array
def onclick(self,event):
self.omega.append((int(round(event.ydata)), int(round(event.xdata))))
def indices(self):
plot = plt.imshow(self.array, cmap = plt.cm.hot, interpolation = 'nearest', origin= 'upper')
fig = plt.gcf()
ax = plt.gca()
zeta = fig.canvas.mpl_connect('button_press_event', self.onclick)
plt.colorbar()
plt.show()
return self.omega
Usage would be something like:
from collect_points import collect_points
import numpy as np
array = np.random.rand(10,10)*255
indices = collect_points(array).indices()
A plotting window should appear, you click on points, and returned are the indices of the numpy array.
Upvotes: 1
Reputation: 11
The above solution only works for a single image. If you plot two or more images in the same script, the "inaxes" event will not make a difference between both axis. You will never know in which axis are you clicking, so you won't know which image value should be displayed.
Upvotes: 1
Reputation: 43680
Here's a passable solution. It only works for interpolation = 'nearest'
. I'm still looking for a cleaner way to retrieve the interpolated value from the image (rather than rounding the picked x,y and selecting from the original array.) Anyway:
from matplotlib import pyplot as plt
import numpy as np
im = plt.imshow(np.random.rand(10,10)*255, interpolation='nearest')
fig = plt.gcf()
ax = plt.gca()
class EventHandler:
def __init__(self):
fig.canvas.mpl_connect('button_press_event', self.onpress)
def onpress(self, event):
if event.inaxes!=ax:
return
xi, yi = (int(round(n)) for n in (event.xdata, event.ydata))
value = im.get_array()[xi,yi]
color = im.cmap(im.norm(value))
print xi,yi,value,color
handler = EventHandler()
plt.show()
Upvotes: 10