How to use the picker to manipulate plots

To manipulate the data, we need to add an extra keyword argument called picker to our plot, as well as a new function called gravity as shown in the following points:

  1.  What this does is calculate the gravitational force between the particle points within the plot:
# Using pick_event & picker to move points
plt.plot(np.random.rand(100), np.random.rand(100), 'ko', picker=5)
def gravity(event):
thispoint = event.artist
ind = event.ind[0]
xpos = thispoint.get_xdata()
ypos = thispoint.get_ydata()
# Calculate the distance to other particles, update their positions with a r^-2 law
rpos = np.linalg.norm([xpos-xpos[ind],ypos-ypos[ind]], axis=0)
thispoint.set_xdata(xpos - 1e-3*(xpos - xpos[ind])/(1e-
9+rpos*rpos))
thispoint.set_ydata(ypos - 1e-3*(ypos - ypos[ind])/(1e
9+rpos*rpos))
plt.gcf().canvas.draw()

cid = plt.gcf().canvas.mpl_connect('pick_event', gravity)

When we run the preceding code, we get the following output:

  1. We can also change the position of the particles and change their colors as well, as shown in the following code:
# Changing colors with pick_event
plt.scatter(np.random.rand(100), np.random.rand(100),
c=np.random.rand(100), s=80, picker=5, edgecolor='none')
def color(event):
# Get the artist object that has been picked
thispoint = event.artist
# Get the element (point in this case) that has been picked
ind = event.ind
# Get the old face colors
newcolor = thispoint.get_facecolors()
# Zero out and re-set the colors
newcolor[ind] = [0.5,0.5,0.5,1]
thispoint.set_facecolors(newcolor)
plt.gcf().canvas.draw()
plt.gcf().canvas.mpl_connect('pick_event', color)
  1. By using this code, we get a scatterplot with randomized colors:

  1. When we select any elements, the color changes to gray, as follows:

Therefore, we can manipulate any of the standard artist objects and attributes.

To manipulate plot objects, the elements of lines, points, and so on, you can use the pick event. By using the pick event, you can change anything that you can change manually, such as size, hatches, fill, edge colors, and even text.

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

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