Python Forum
Pick a line in a plot with matplotlib
Thread Rating:
  • 1 Vote(s) - 2 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Pick a line in a plot with matplotlib
#1
Hi all.

I have an issue with a picking event using the matplotlib library. I am trying to pick a vertical line that I draw on a X-Y plot when I click near the line. However, wherever I click, the line is picked, and I do not understand why.

Here's my code:

import numpy as np
import matplotlib.pyplot as plt

class my_class:
    def __init__( self , **kwargs ):
        self.fig , self.ax = plt.subplots()
        self.line = self.ax.axvline( x = 0.5 , **kwargs )
        self.connect()
        plt.show()
        return
        
    def connect( self ):
        cid = self.fig.canvas.mpl_connect( 'button_press_event' , self.on_click )
        return
        
    def on_click( self , event ):
        if self.line.contains( event ):
            print( "Line picked." )
        return

def main():
    my_plot = my_class( pickradius = .5 )

if __name__ == "__main__":
    main()
The constructor creates the plot, the line, and connects to mouse events via the function "connect". The function "on_click" is a callback function to mouse clicking events that (should) print "Line picked." whenever I click near the line. But it prints "Line picked" wherever I click.

Any idea?
Reply


Messages In This Thread
Pick a line in a plot with matplotlib - by Romain - Sep-18-2018, 07:21 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  How to create a plot with line graphs and vertical bars devansing 6 2,256 Feb-28-2023, 05:38 PM
Last Post: devansing
  Plot Line chart based on the input parthi1705 4 3,401 Feb-28-2023, 12:08 PM
Last Post: get2sid
  Help to Plot timeline for intreruption of one line production danut_horincas 2 2,506 Feb-28-2023, 11:48 AM
Last Post: get2sid
  Matplotlib scatter plot in loop with None values ivan_sc 1 2,236 Nov-04-2021, 11:25 PM
Last Post: jefsummers
  Matplotlib scatter plot slider with datetime sonny 0 2,919 Feb-05-2021, 02:31 AM
Last Post: sonny
  New to Python & Matplotlib - can I change the plot grid origin to lower left corner? FortyTwo 1 6,098 Aug-22-2020, 08:22 PM
Last Post: matador
  matplotlib creating a scatter plot via PathCollection tpourjalali 0 2,430 Apr-11-2020, 05:59 PM
Last Post: tpourjalali
  Learning indexing with python, pick dates dervast 1 1,720 Jul-11-2019, 07:29 AM
Last Post: scidam
  MatPlotLib 2d plot of current density? ruben 0 2,171 May-13-2019, 06:47 AM
Last Post: ruben
  Bar Plot with Python ,matplotlib and sqlite3 tables gauravbhardwajee 0 4,928 Sep-25-2018, 06:17 PM
Last Post: gauravbhardwajee

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020