Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

canvas.mpl_connect in jupyter notebook

Tags:

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!

like image 874
Meng Avatar asked May 11 '17 18:05

Meng


People also ask

What does %% capture do in Jupyter?

IPython has a cell magic, %%capture , which captures the stdout/stderr of a cell. With this magic you can discard these streams or store them in a variable. By default, %%capture discards these streams. This is a simple way to suppress unwanted output.

How do I set Environment path in Jupyter notebook?

To set an env variable in a jupyter notebook, just use a % magic commands, either %env or %set_env , e.g., %env MY_VAR=MY_VALUE or %env MY_VAR MY_VALUE . (Use %env by itself to print out current environmental variables.)

How do you print screen on a Jupyter notebook?

Open jupyter-shot. ipynb and run the cells. You should then be able to select any cell and press r to see a screenshot of the cell appear in a new window with an Imgur url.

How do I display an image in Ipynb?

First, you need to encode your image. For this, you can use the online tool Base64-Image. After you upload your image, you can then click on the copy image, as shown below. Now you can paste the encoded image code into your notebook, but first, you should remove data:image/png;base64, at the beginning.


1 Answers

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)
    

enter image description here

like image 107
ImportanceOfBeingErnest Avatar answered Sep 22 '22 06:09

ImportanceOfBeingErnest