jupyter笔记本中的canvas.mpl_connect [英] canvas.mpl_connect in jupyter notebook

查看:623
本文介绍了jupyter笔记本中的canvas.mpl_connect的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在test.py中有以下代码:

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)

当我在命令行中通过"python test.py"运行test.py时,将"button =%d,x =%d,y =%d,xdata =%f,ydata =%f"打印为我点击情节

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

但是,结果不会在jupyter笔记本中打印.

however, the results are not printed in jupyter notebook.

如何解决?

提前谢谢!

推荐答案

这将取决于您在jupyter笔记本中使用哪个后端.

It will depend which backend you use in jupyter notebook.

  • 如果您使用嵌入式后端(即%matplotlib inline),则交互式功能将不起作用,因为绘图只是png图像.
  • 如果使用笔记本后端(即%matplotlib 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)

这篇关于jupyter笔记本中的canvas.mpl_connect的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆