使用 matplotlib ginput 收集鼠标单击位置并通过位置绘制垂直线

问题描述

我正在尝试使用 ginput 收集一系列鼠标单击位置,每次通过在每次单击时绘制一条垂直线来更新绘图:

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)

这可以正常工作,因为它正确存储了所有点击位置,但它只在每第二次点击时绘制垂直线,我不明白为什么会发生这种情况。

我正在使用

Python 3.9.2(认,2021 年 2 月 24 日,13:30:36) [Clang 12.0.0 (clang-1200.0.32.29)] 在达尔文

和 matplotlib 3.3.4 版

解决方法

好吧,我刚刚意识到发生了什么,正在绘制线条,但直到单击 ginput 后​​该图才更新,所以我误解了这一点,因为似乎我需要在某个位置单击两次才能获得那里有一条线。 Using the solution from this post,添加暂停命令解决了这个问题:

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