jupyter / notebook

Jupyter Interactive Notebook
https://jupyter-notebook.readthedocs.io/
BSD 3-Clause "New" or "Revised" License
11.72k stars 4.95k forks source link

Debugging interactive plots in a Jupyter notebook #5271

Open jkitchin opened 4 years ago

jkitchin commented 4 years ago

The example below should highlight the point that you click on, and change the title of the graph to show the label associated with that point.

If I run this Python script as a script, when I click on a point I will get an error " line 15, in onpick TypeError: only integer scalar arrays can be converted to a scalar index", which is expected. event.ind is a list, and I need to change that to ind = event.ind[0] to be correct here.

However, when I run this in a Jupyter notebook, the figure appears, but the error is silently ignored, so it just appears that the code does not work. Is there a way to get Jupyter to show me that an error has occurred?

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()
f0k commented 5 months ago

This is currently one of the top results for this question in a major search engine. For people from the future: When using jupyterlab with ipympl, then as described in the ipympl documentation, the errors can either be looked at in the jupyterlab log console (View > Show Log Console), or captured via an ipywidgets widgets.Output:

out = widgets.Output()
@out.capture()
def onpick(event):
    ...

I do not know whether this also works in a classic notebook, which this question was about, but wanted to leave this trace for others.