How to add interactivity to these widgets using callbacks

Just like with the slider, we can add a callback in the code that will change the color of our output. By doing this, we can switch between cyan, blue, and black:

# Radio Buttons
ax1 = plt.axes([0.05, 0.1, 0.65, 0.8])
curve, = ax1.plot(nums, np.sin(nums))
ax2 = plt.axes([0.75, 0.1, 0.15, 0.3])
colors = ('cyan', 'blue', 'black')
color = RadioButtons(ax2, colors)
def setcolor(color):
curve.set_color(color)
plt.gcf().canvas.draw()
# color.on_clicked(setcolor)

We will get the following code:

Now, we want to use a selector to select the points in the plot. By doing this, we can generate the selector and add a callback for it. Let's take a look at this callback in passing—you might think from the fact that this is called a rectangle selector that arguments to the callback would be a selection of points—perhaps a line segment—but actually all that gets passed are two events, E1 and E2. The first event is where you click; the second event is where you release the mouse so that these two events cover the two corners of the rectangle that gets drawn:

# Using widgets with callbacks
ax1 = plt.subplot(111)
xpts = np.random.rand(100)
ypts = np.random.rand(100)
s = 10*np.ones(100)
points = ax1.scatter(xpts, ypts, s=s, c='b')
ax1.set_xlim(0,1)
ax1.set_ylim(0,1)
def changepoints(e1, e2):
x0, x1 = sorted([e1.xdata, e2.xdata])
y0, y1 = sorted([e1.ydata, e2.ydata])
sizes = points.get_sizes()
sizes[np.where((xpts > x0) & (xpts < x1) & (ypts > y0) & (ypts <
y1))] = 50
points.set_sizes(sizes)
plt.gcf().canvas.draw()
rect = RectangleSelector(ax1, onselect=changepoints)

To actually select these points, we need to draw a rectangle in this plot and then select where the values of the x and y positions fall within that rectangle:

The callback takes the points that have been grabbed within the rectangle selector and increases their size.

This is why here, we can see that the selection is based on the edges of the points that have their X and Y positions within that rectangle. We have also set their sizes using the set_sizes method on the return value of that scatterplot by using the canvas.draw( ) method.

Now, we have seen the workings of the GUI network inside the Jupyter Notebook. We can also do the same outside of the Jupyter Notebook.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset