2017-10-03 2 views
0

플롯에 선을 그리려면 button_press_events를 사용하고 싶습니다. 다음 코드는 그렇게하지만 라인 좌표는 서로 뒤 따릅니다.button_press_event를 사용하여 플롯에 별도의 선을 그립니다.

import numpy as np 
import matplotlib.pyplot as plt 

fig = plt.figure() 
ax = fig.add_subplot(111) 
# Plot some random data 
values = np.random.rand(4,1); 
graph_1, = ax.plot(values, label='original curve') 
graph_2, = ax.plot([], marker='.') 

# Keep track of x/y coordinates 
xcoords = [] 
ycoords = [] 

def onclick(event): 
    xcoords.append(event.xdata) 
    ycoords.append(event.ydata) 

    # Update plotted coordinates 
    graph_2.set_xdata(xcoords) 
    graph_2.set_ydata(ycoords) 

    # Refresh the plot 
    fig.canvas.draw() 

cid = fig.canvas.mpl_connect('button_press_event', onclick) 
plt.show() 

enter image description here

어떻게 그렇게 이벤트 별도의 행마다 두 번째 클릭 결과를 구분합니까?

답변

0

트릭을해야합니다. 이 코드에서 개선해야 할 사항은 축 내부 또는 외부에서 클릭이 감지되었는지 여부를 감지하는 것과 같지만 올바른 추적을해야한다는 것입니다.

fig = plt.figure() 
ax = fig.add_subplot(111) 
# Plot some random data 
values = np.random.rand(4,1); 
graph_1, = ax.plot(values, label='original curve') 

# Keep track of x/y coordinates 
lines = [] 
xcoords = [] 
ycoords = [] 

def onclick(event): 
    xcoords.append(event.xdata) 
    ycoords.append(event.ydata) 
    if len(xcoords)==2: 
     lines.append(ax.plot(xcoords,ycoords,'.-')) 
     xcoords[:] = [] 
     ycoords[:] = [] 

    # Refresh the plot 
    fig.canvas.draw() 

cid = fig.canvas.mpl_connect('button_press_event', onclick) 
plt.show() 

enter image description here

+0

많은 감사,이 완벽하게 작동합니다. –

관련 문제