Matplotlib – Lasso Selector Widget
Last Updated :
23 Feb, 2021
Matplotlib provides us with a variety of widgets. In this article, we will be learning about Lasso Selector Widget Demo. A Lasso Selector Widget is a tool that helps us to make a selection curve of arbitrary space.
Approach #1
We will be adding the axes manually to our plot and then use the lasso-selector-widget tool.
Implementation:
Python3
import matplotlib.pyplot as plt
from matplotlib.widgets import LassoSelector
fig = plt.figure()
axes = fig.add_axes([ 0.1 , 0.1 , 0.8 , 0.8 ])
axes.set_xlabel( 'X-axis' )
axes.set_ylabel( 'Y-Axis' )
axes.set_title( 'LassoSelector-Demo-Widget' )
def onSelect(geeksforgeeks):
print (geeksforgeeks)
line = { 'color' : 'green' ,
'linewidth' : 8 , 'alpha' : 1 }
lsso = LassoSelector(ax = axes, onselect = onSelect,
lineprops = line, button = 2 )
plt.show()
|
Output:
Explanation:
In the above code, we are importing matplotlib package to our python project along with the LassoSelector tool from the matplotlib.widgets module. After importing the packages, we are creating a figure(i.e an empty canvas) and adding axes to it manually. Then, we are defining a function onSelect() that gets triggered as soon as the mouse is pressed in the plot. Then, we are creating line that defines the properties of the line, and then comes LassoSelector which helps us to draw inside the plots. Now inside LassoSelector there are four parameters, the first one defines the axes that we have created, the second one defines the onSelect() function, the third parameter is defining the properties of the line(line) and the last parameter defines which click of the mouse will be used to draw the plot(left, right, middle).
Approach #2
Here, Instead of manually adding axes, we can also do it using plt.subplots which automatically creates axes.
Python3
import matplotlib.pyplot as plt
from matplotlib.widgets import LassoSelector
fig, axes = plt.subplots()
axes.set_xlabel( 'X-axis' )
axes.set_ylabel( 'Y-Axis' )
axes.set_title(
'LassoSelector-Demo-Widget with axes created automatically with subplots' )
def onSelect(geeksforgeeks):
print (geeksforgeeks)
line = { 'color' : 'green' ,
'linewidth' : 8 , 'alpha' : 1 }
lsso = LassoSelector(ax = axes, onselect = onSelect,
lineprops = line, button = 2 )
plt.show()
|
Output:
Explanation:
The same series of events are taking place just like our previous approach. The only difference is that here we are automatically creating axes with the help of plt.subplots(). If you go through the terminal, you can see a large number of coordinates which are the points on which we have drawn in the graph.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...