python - 在 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()
提前致谢。
解决方案
这应该让你开始:
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)
推荐阅读
- oracle - 使用 Oracle EBS 将数据发送到 Azure
- javascript - 如何访问 Vue.js 中的动态元素?
- uml - 什么是最适合基于以下场景建模的 UML 图?
- search - emacs:在区域上搜索和替换
- winforms - 安装 WinForm 应用程序后指定文件类型图标下不需要的常规图标
- ios - iOS 13 In Tab Bar子视图控制器viewWillAppear未被调用
- vue.js - Vue CLI 3 使用 Terser 删除 console.log 和代码注释
- android - 小米 Redmi 7 无法在 IDE 中使用 USB
- rxjs - rxjs 订阅被调用的频率高于预期
- entity-framework - EF 核心是否比较值以包含更新语句中的列?