在Jupyter笔记本中调试交互式Matplotlib图形

时间:2020-03-06 12:32:00

标签: matplotlib jupyter-notebook interactive

下面的示例应突出显示您单击的点,并更改图形标题以显示与该点关联的标签。

如果我将此Python脚本作为脚本运行,当我单击某个点时,将在onpick中出现错误“第15行” TypeError:只能将整数标量数组转换为标量索引。” event.ind是一个列表,我需要将其更改为ind = event.ind[0]才能正确。

但是,当我在Jupyter笔记本中运行该图形时,会出现该图,但该错误被默默忽略,因此看起来该代码不起作用。有没有办法让Jupyter告诉我发生了错误?

import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

x = [0, 1, 2, 3, 4, 5]
labels = ['a', 'b', 'c', 'd', 'e', 'f']
ax.plot(x, 'bo', picker=5)

# this is the transparent marker for the selected data point
marker, = ax.plot([0], [0], 'yo', visible=False, alpha=0.8, ms=15)

def onpick(event):
    ind = event.ind
    ax.set_title('Data point {0} is labeled "{1}"'.format(ind, labels[ind]))
    marker.set_visible(True)
    marker.set_xdata(x[ind])
    marker.set_ydata(x[ind])

    ax.figure.canvas.draw()  # this line is critical to change the linewidth

fig.canvas.mpl_connect('pick_event', onpick)

plt.show()

0 个答案:

没有答案