collect mouse click location with matplotlib ginput and draw vertical line through location

623 views Asked by At

I'm trying to collect a series of mouse click locations using ginput,updating the plot each time by drawing a vertical line through each click:

import numpy as np
import matplotlib.pyplot as plt

x=np.arange(10)
y=x**2

fig,ax=plt.subplots()

times=[]

ax.plot(x,y)

while True:
    pts=plt.ginput(1)
    time=pts[0][0]  
    times.append(time)
    ax.axvline(x=time)
    # click on right side to escape
    if (time>8.5): 
        break

print ("final=",times)

This works as in it stores all the click locations correctly, BUT it only draws vertical lines every second click, and I don't see why this is happening.

I'm using

Python 3.9.2 (default, Feb 24 2021, 13:30:36) [Clang 12.0.0 (clang-1200.0.32.29)] on darwin

and matplotlib version 3.3.4

1

There are 1 answers

0
ClimateUnboxed On

Okay I've just realized what is going on, the line was being plotted but the figure was not updated until the following click on ginput, so I had misinterpreted this as it seemed I needed to click in a location twice to get a line there. Using the solution from this post, the addition of a pause command solves the issue:

import numpy as np
import matplotlib.pyplot as plt

x=np.arange(10)
y=x**2

fig,ax=plt.subplots()

times=[]

ax.plot(x,y)

while True:
    pts=plt.ginput(1)
    time=pts[0][0]  
    times.append(time)
    ax.axvline(x=time)
    plt.pause(0.05)
    if (time>8.5):
        break