Interactive plots in Jupyter (IPython) notebook with draggable points that call Python code when dragged

后端 未结 2 1575
太阳男子
太阳男子 2021-02-19 00:52

I\'d like to make some interactive plots in the Jupyter notebook, in which certain points in the plot can be dragged by the user. The locations of those points should then be u

2条回答
  •  感动是毒
    2021-02-19 01:24

    Have you tried bqplot? The Scatter has an enable_move parameter, that when you set to True they allow points to be dragged. Furthermore, when you drag you can observe a change in the x or y value of the Scatter or Label and trigger a python function through that, which in turn generates a new plot. They do this in the Introduction notebook.

    Jupyter notebook code:

    # Let's begin by importing some libraries we'll need
    import numpy as np
    from __future__ import print_function # So that this notebook becomes both Python 2 and Python 3 compatible
    
    # And creating some random data
    size = 10
    np.random.seed(0)
    x_data = np.arange(size)
    y_data = np.cumsum(np.random.randn(size)  * 100.0)
    
    from bqplot import pyplot as plt
    
    # Creating a new Figure and setting it's title
    plt.figure(title='My Second Chart')
    # Let's assign the scatter plot to a variable
    scatter_plot = plt.scatter(x_data, y_data)
    
    # Let's show the plot
    plt.show()
    
    # then enable modification and attach a callback function:
    
    def foo(change):
        print('This is a trait change. Foo was called by the fact that we moved the Scatter')
        print('In fact, the Scatter plot sent us all the new data: ')
        print('To access the data, try modifying the function and printing the data variable')
        global pdata 
        pdata = [scatter_plot.x,scatter_plot.y]
    
    # First, we hook up our function `foo` to the colors attribute (or Trait) of the scatter plot
    scatter_plot.observe(foo, ['y','x'])
    
    scatter_plot.enable_move = True
    

提交回复
热议问题