'Picking points interactively using matplotlib
I was wondering if anyone is able to explain why the artist (thisline) object is of type PathCollection, rather than of type Line2D. A working example of the problem is provided below, wherein the user is asked to click on as many points as they want, before confirming that they are happy with their selection.
import matplotlib.pyplot as plt
import numpy as np
def get_segments():
'''
Gets the x,y points defining the segments of the fence that the user wishes
to investigate
'''
# Define a function that changes points colours when clicked and extracts the points' x,y
def onpick(event):
thisline = event.artist
xdat = thisline.get_xdata()
ydat = thisline.get_ydata()
x_clicked.append(xdat)
y_clicked.append(ydat)
ind = event.ind
print('x: '+str(fence_x[ind])+', y: '+str(fence_y[ind])+' clicked.')
coll._facecolors[ind,:] = (1, 0, 0, 1)
coll._edgecolors[ind,:] = (1, 0, 0, 1)
fig.canvas.draw()
# Make a fence
fence_x = [1.0,1.0,2.0,2.0]
fence_y = [1.0,2.0,2.0,1.0]
happy = False # The user is not happy with their selection
input_msg = 'Please click on the first and the last points of the region of the fence you are interested in'
while not happy:
print(input_msg)
x_clicked = []
y_clicked = []
fig, ax = plt.subplots()
line = ax.plot(fence_x,fence_y,'k')
coll = ax.scatter(fence_x,fence_y,color=['blue']*len(fence_x),picker=True,pickradius=0.01)
ax.set_aspect('equal')
ax.set_xlabel('x(m)')
ax.set_ylabel('y(m)')
ax.set_title('Fence segment selector')
fig.canvas.mpl_connect('pick_event',onpick)
plt.show()
print('Are you happy with your selection? (y/n):')
happy_check = str(input())
if happy_check == 'y':
happy = True
plt.clf()
plt.close()
if __name__ == '__main__':
get_segments()
Cheers
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
