3

I have a colorbar and a graph. I was wondering if you can use the onclick method on a colorbar that will then do something on the graph. So click on a particular color portion of the colorer then something happens I know how to do the bit that i want to happen. I just want to know how to set the colorbar to allow on click

1 Answer 1

6

Sure! Just do something like cbar.ax.set_picker(tolerance).

As a quick example, this will highlight values in the image near the value you click on the colorbar:

import numpy as np
import matplotlib.pyplot as plt

data = np.random.random((10,10))

fig, ax = plt.subplots()
im = ax.imshow(data)
cbar = fig.colorbar(im)
ax.set_title('Click on the colorbar')

highlight = ax.imshow(np.ma.masked_all_like(data), interpolation='nearest', 
                      vmin=data.min(), vmax=data.max())

def on_pick(event):
    val = event.mouseevent.ydata
    selection = np.ma.masked_outside(data, val - 0.05, val + 0.05)
    highlight.set_data(selection)
    fig.canvas.draw()

cbar.ax.set_picker(5)
fig.canvas.mpl_connect('pick_event', on_pick)

plt.show()

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for this. I was trying to use mouse click events and realized that event.inaxes could never be cbar.ax, so a picker is a very nice solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.