通过读取txt文档,获取其中的x,y数据,也可以自己生成数据,但是数据量越大,整体运行出来就越流畅,如果数据量小,可以看起来就比较卡顿。感谢大神放出代码! 参考文章:Python鼠标拖动曲线(matplotlib)_曲线模拟鼠标滑动算法-CSDN博客 import matplotlib.pyplot as plt # 导入画图的包matplotlib import numpy as np from scipy.optimize import curve_fit # 导入拟合曲线方程的包 def data_read(file): lines = file.readlines() x=[] y=[] base=[] for i in range(1,len(lines)): data = lines[i] split_data = data.split('\t') a=float(split_data[1]) x .append(float(split_data[0])) y.append(a) # 关闭文件 file.close() return x,y file=open(r"D:\平.txt",'r') x,y=data_read(file) # 先生成一群点,把点画出来 fig, ax = plt.subplots() scatterx=[x[0],x[len(x)-1]] scattery=[ y[0],y[len(x)-1]] global ind global select_flag ind=[] select_flag=False # 忽略除以0的报错 np.seterr(divide='ignore', invalid='ignore') scatter = ax.scatter(scatterx, scattery, picker=5) plt.plot(x,y) def on_button_press(event): fig.canvas.mpl_connect('motion_notify_event', on_button_move) def find_xy(x,y,x_rec): if x_rec>=x[len(x)-1]: xi=x[len(x)-1] yi=y[len(y)-1] elif x_rec<=x[0]: xi = x[0] yi = y[0] else: for i in range(len(x)): if x[i]<x_rec<=x[i+1]: xi=x[i+1] yi=y[i+1] return xi,yi # on_button_move 鼠标移动事件 def on_button_move(event, y=y): ind = [] select_flag = False if event.button == 1: # 1、2、3分别代表鼠标的左键、中键、右键,我这里用的是鼠标中键,根据自己的喜好选择吧 x_mouse, y_mouse = event.xdata, event.ydata # 拿到鼠标当前的横纵坐标 # 计算一下鼠标的位置和图上点的位置距离,如果距离很近就移动图上那个点 if not select_flag: for i in range(len(scatterx)): # 计算一下距离 图上每个点都和鼠标计算一下距离 d = np.sqrt((x_mouse - scatterx[i]) ** 2 + (y_mouse - scattery[i]) ** 2) if d < scatter.get_picker(): # 这里设置一个阈值,如果距离很近,就把它添加到那个列表中去 ind.append(i) if ind: select_flag = True if select_flag: scatterx[ind[0]],scattery[ind[0]]=find_xy(x,y,x_mouse) ax.cla() ax.scatter(scatterx, scattery) ax.plot(x,y) fig.canvas.draw_idle() # 鼠标释放事件,鼠标松开的时候,就把上面鼠标点击并且移动的关系解绑 这样鼠标松开的时候 就不会拖动点了 def on_button_release(event): ind = [] select_flag = False fig.canvas.mpl_disconnect(fig.canvas.mpl_connect('motion_notify_event', on_button_move)) # 鼠标释放事件 fig.canvas.mpl_disconnect(fig.canvas.manager.key_press_handler_id) # 取消默认快捷键的注册, fig.canvas.mpl_connect('button_press_event', on_button_press) # 鼠标点击事件 fig.canvas.mpl_connect('button_release_event', on_button_release) # 鼠标松开 plt.show() # 显示图像
09-13
9477
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交