canvas.mpl_connect in jupyter notebook

匿名 (未验证) 提交于 2019-12-03 01:27:01

问题:

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!

回答1:

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)



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!