A selection of the different kinds of widgets that are available in Matplotlib

The different selections in Matplotlib are as follows:

  1. Generate two axes objects, one that is going to contain a curve and another that is long and thin beneath it, as follows:
# Slider
ax1 = plt.axes([0.25, 0.2, 0.65, 0.7])
curve, = ax1.plot(nums, np.sin(nums))
ax1.set_ylim(-10,10)
ax2 = plt.axes([0.25, 0.1, 0.65, 0.03])
def redraw(value):
curve.set_ydata(value*np.sin(nums))
plt.gcf().canvas.draw()
amp.on_changed(redraw)

We will get the following output:

  1. Using the long and thin axis underneath, generate a slider, give it ax2 (the long thin one), and call it amplitude. The sliders also have a range; give it a range between 0 and 10, as shown in the following code:
# Slider
ax1 = plt.axes([0.25, 0.2, 0.65, 0.7])
curve, = ax1.plot(nums, np.sin(nums))
ax1.set_ylim(-10,10)
ax2 = plt.axes([0.25, 0.1, 0.65, 0.03])
amp = Slider(ax2, 'Amplitude', 0.1, 10, valinit=2)
def redraw(value):
curve.set_ydata(value*np.sin(nums))
plt.gcf().canvas.draw()
# amp.on_changed(redraw)

When we run the preceding code, we get a little slider widget below the plot. Now, when we click on the slider, it actually changes the value of that slider and the values displayed, as follows:

Most of the widgets have methods so that we can apply callbacks on them. In this case, we have the unchanged method for our slider, and we can pass a function that will change the value of this curve.

  1. We can generate another set of axes where we have a tiny little box in the corner. By adding a radio button object to that little box with a list as its second argument, colors, we can actually fill in a nice little radio button:
# 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')
def setcolor(color):
curve.set_color(color)
plt.gcf().canvas.draw()
# color.on_clicked(setcolor)

The radio button can also be clicked, as shown in the following output:

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

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