Color values ​​in imshow for matplotlib?

I would like to know the color value of the dot that I click when I use imshow () in matplotlib. Is there a way to find this information through an event handler in matplotlib (just like the x, y coordinates of your click are available)? If not, how can I find this information?

In particular, I think of such a case:

imshow(np.random.rand(10,10)*255, interpolation='nearest') 

Thanks! --Erin

+8
python matplotlib
source share
4 answers

Here is a passable solution. It only works for interpolation = 'nearest' . I'm still looking for a cleaner way to get the interpolated value from the image (instead of rounding the selected 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() 
+10
source share

The above solution only works for one image. If you draw two or more images in the same script, the inaxes event will not have a difference between the two axes. You will never know which axis you click on, so you will not know what image value should be displayed.

+1
source share

If by "color value" you understand the value of the array at the click point on the chart, 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 will be something like this:

 from collect_points import collect_points import numpy as np array = np.random.rand(10,10)*255 indices = collect_points(array).indices() 

A build window should appear, you click on the points and return the indices of the numpy array.

+1
source share

You can try something like 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') 
0
source share

All Articles