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
#2
You could perhaps try an integer pickradius such as 5
Reply
#3
Thanks for the answer Gribouillis.

I tried that, but it still picks the line wherever I click.
Reply
#4
The issue with your code is that the contains method of the Line2D object returned by axvline is always returning True, regardless of where you click, because you're not checking if the click is within a certain distance of the line.

To fix this, you can calculate the distance between the click event and the line using the dist method of the Line2D object. Here's the updated on_click method that should work correctly:

def on_click(self, event):
if event.inaxes == self.ax:
distance = abs(event.xdata - self.line.get_xdata()[0])
if distance < self.ax.get_xbound()[1] * 0.01:
print("Line picked.")
return


This code first checks if the click event is within the axes of the plot. Then, it calculates the distance between the x-coordinate of the click event and the x-coordinate of the line using the get_xdata method. Finally, it checks if the distance is less than 1% of the x-axis range of the plot, and prints "Line picked." if it is.

You can adjust the 0.01 factor to change the sensitivity of the picking event. In this case, it checks if the click is within 1% of the x-axis range of the plot, but you can adjust this to make it more or less sensitive depending on your needs.

I hope this helps!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to create a plot with line graphs and vertical bars devansing 6 2,254 Feb-28-2023, 05:38 PM
Last Post: devansing
  Plot Line chart based on the input parthi1705 4 3,399 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,234 Nov-04-2021, 11:25 PM
Last Post: jefsummers
  Matplotlib scatter plot slider with datetime sonny 0 2,918 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,095 Aug-22-2020, 08:22 PM
Last Post: matador
  matplotlib creating a scatter plot via PathCollection tpourjalali 0 2,429 Apr-11-2020, 05:59 PM
Last Post: tpourjalali
  Learning indexing with python, pick dates dervast 1 1,716 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