-1
votes

Here is my sample code on jupyter notebook:

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(np.random.rand(10))

def onclick(event):
    print('button=%d, x=%d, y=%d, xdata=%f, ydata=%f' %
          (event.button, event.x, event.y, event.xdata, event.ydata))

cid = fig.canvas.mpl_connect('button_press_event', onclick)
1
Jupyter by default shows png images of the plot. Do you want to be able to click on the png image, or do you want to plot an interactive plot where matplotlib click events are working? And where would you like the result to be printed? - ImportanceOfBeingErnest

1 Answers

2
votes

Jupyter by default shows png images of the plot. In order to get an interactive figure, you would need the %matplotlib notebook backend.

The next problem is that it's currently not possible to interactively print to the cell output. This exact example is already subject of this GitHub issue. A solution may be expected for matplotlib version 2.1.

As of now you might want to print the output to the figure canvas, e.g. as figure title.

To give an example:

import matplotlib.pyplot as plt
import numpy as np
%matplotlib notebook 

fig = plt.figure();
ax = fig.add_subplot(111)
ax.plot(np.random.rand(10))

def onclick(event):
    a = ('button=%d, x=%d, y=%d, xdata=%f, ydata=%f' %
          (event.button, event.x, event.y, event.xdata, event.ydata))
    ax.set_title(a)

cid = fig.canvas.mpl_connect('button_press_event', onclick)

plt.show()

enter image description here