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

查看:51
本文介绍了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 notebook 中.

however, the results are not printed in jupyter notebook.

如何解决?

提前致谢!

推荐答案

这将取决于您在 jupyter notebook 中使用的后端.

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天全站免登陆