首页 > 解决方案 > 在 Matplotlib 画布上绘制单独的线并将坐标写入数据框

问题描述

我从这里得到了解决方案:matplotlib onclick event repeating

我想更改此代码,因此当我单击画布两次时,该行在第二次单击时完成。第三次点击应该是一个全新行的第一个点,而不是一个延续。

另外,有没有办法将创建的每条线的 x,y 和 x1,y1 的坐标写入数据帧?

代码:

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='o')

# 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()

提前致谢。

标签: pythonpandasmatplotlibcanvas

解决方案


这应该让你开始:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

coords = []
current_coords = []


def onclick(event):
    global current_coords
    if event.inaxes:
        current_coords.append((event.xdata, event.ydata))
        if len(current_coords) == 2:
            ax.plot([current_coords[0][0], current_coords[1][0]],
                    [current_coords[0][1], current_coords[1][1]], 'ro-')
            coords.append([current_coords[0], current_coords[1]])
            current_coords[:] = []

        # Refresh the plot
        fig.canvas.draw()


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

该变量coords包含一个坐标列表。每一项都是一个列表[(x0,y0),(x1,y1)]

编辑 此版本的代码仅显示一行,并响应鼠标单击和按键盘上的“a”键

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

coords = []
current_coords = []
l, = ax.plot([], [], 'ro-')


def onclick(event):
    global current_coords
    if event.inaxes:
        current_coords.append((event.xdata, event.ydata))
        if len(current_coords) == 2:
            l.set_data([current_coords[0][0], current_coords[1][0]],
                       [current_coords[0][1], current_coords[1][1]])
            coords.append([current_coords[0], current_coords[1]])
            current_coords[:] = []

        # Refresh the plot
        fig.canvas.draw()


def onkey(event):
    if event.key == 'a':
        onclick(event)


cid = fig.canvas.mpl_connect('button_press_event', onclick)
cid2 = fig.canvas.mpl_connect('key_press_event', onkey)
plt.show()
print(coords)

推荐阅读