25

I have the following code in test.py:

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)

when i run test.py in the command line by "python test.py", 'button=%d, x=%d, y=%d, xdata=%f, ydata=%f' gets printed as i click the plot

however, the results are not printed in jupyter notebook.

how to fix it?

thanks in advance!

Meng
  • 1,148
  • 5
  • 15
  • 23

1 Answers1

32

It will depend which backend you use in jupyter notebook.

  • If you use the inline backend (i.e. %matplotlib inline), interactive features cannot work, because the plots are just png images.
  • If you use the notebook backend (i.e. %matplotlib notebook) the interactive features do work, but the question would be where to print the result to. So in order to show the text one may add it to the figure as follows

    %matplotlib notebook
    import numpy as np
    import matplotlib.pyplot as plt
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.plot(np.random.rand(10))
    text=ax.text(0,0, "", va="bottom", ha="left")
    
    def onclick(event):
        tx = 'button=%d, x=%d, y=%d, xdata=%f, ydata=%f' % (event.button, event.x, event.y, event.xdata, event.ydata)
        text.set_text(tx)
    
    cid = fig.canvas.mpl_connect('button_press_event', onclick)
    

enter image description here

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
  • 2
    Great solution. Too bad the matplotlib notebook doesn't connect to the regular print() command. – shahar_m Oct 16 '17 at 06:47
  • And in the gui backends, the interactive features and printing both work, but the graph is in a separate window instead of in the notebook. – Spirko Feb 01 '18 at 07:42
  • 1
    To anyone looking for an answer: using the magic commands `%matplotlib widget` or `%matplotlib ipympl` (requires ipympl package) allows for normal print commands. – user2831602 Jul 18 '18 at 13:41
  • 1
    When I run the code above I get, Javascript Error: IPython is not defined. The line that causes it is 'fig = plt.figure()'. Does anyone know why? – stew Aug 17 '20 at 23:37
  • @stew I had the same issue with jupyter lab. https://stackoverflow.com/a/56416229/11756613 this fixed it – racoon_lord Feb 04 '21 at 18:56