Python 使用Matplotlib绘制可拖动的折线
Python 使用Matplotlib绘制可拖动的折线
效果图:
可以拖曲线上的点调整, 也可以拖旁边的sliderbar调整.

代码如下:
import matplotlib.animation as animation
from matplotlib.widgets import Slider, Button
import pandas as pd
import matplotlib as mpl
from matplotlib import pyplot as plt
import scipy.interpolate as inter
import numpy as np func = lambda x: np.zeros_like(x) def load_cache_weight(cache_file):
import yaml
global yvals
with open(cache_file,'r') as f:
line = f.readline()
d = dict(yaml.safe_load(line))
keys = d.keys()
for i, key in enumerate(keys):
yvals[i] = d[key] # user input config
N = 30
st = pd.to_datetime('20230414')
cache_file = None
cache_file = './tmp/saved_weight_2.json'
save_file = './tmp/saved_weight_2.json' #get a list of points to fit a spline to as well
xmin = 1
xmax = N+1
x = np.linspace(xmin,xmax,N) #spline fit
yvals = func(x)
if cache_file is not None:
load_cache_weight(cache_file)
spline = inter.InterpolatedUnivariateSpline (x, yvals) #figure.subplot.right
mpl.rcParams['figure.subplot.left'] = 0.1
mpl.rcParams['figure.subplot.right'] = 0.8 #set up a plot
fig,axes = plt.subplots(1,1,figsize=(16,5),sharex=True)
ax1 = axes pind = None #active point
epsilon = 5 #max pixel distance def update(val):
global yvals
global spline
# update curve
for i in np.arange(N):
yvals[i] = sliders[i].val
l.set_ydata(yvals)
spline = inter.InterpolatedUnivariateSpline(x, yvals)
m.set_ydata(spline(X))
# redraw canvas while idle
fig.canvas.draw_idle() def reset(event):
global yvals
global spline
#reset the values
yvals = func(x)
if cache_file is not None:
load_cache_weight(cache_file)
for i in np.arange(N):
sliders[i].reset()
spline = inter.InterpolatedUnivariateSpline(x, yvals)
l.set_ydata(yvals)
m.set_ydata(spline(X))
# redraw canvas while idle
fig.canvas.draw_idle() def save_p(event):
global yvals
global datelst
global save_file
r = dict(zip(map(lambda x: x.strftime('%Y%m%d'),datelst),yvals))
print(r)
if save_file is not None:
with open(save_file,'w') as f:
import json
json.dump(r,f) def button_press_callback(event):
'whenever a mouse button is pressed'
global pind
if event.inaxes is None:
return
if event.button != 1:
return
#print(pind)
pind = get_ind_under_point(event) def button_release_callback(event):
'whenever a mouse button is released'
global pind
if event.button != 1:
return
pind = None def get_ind_under_point(event):
'get the index of the vertex under point if within epsilon tolerance' # display coords
#print('display x is: {0}; display y is: {1}'.format(event.x,event.y))
t = ax1.transData.inverted()
tinv = ax1.transData
xy = t.transform([event.x,event.y])
#print('data x is: {0}; data y is: {1}'.format(xy[0],xy[1]))
xr = np.reshape(x,(np.shape(x)[0],1))
yr = np.reshape(yvals,(np.shape(yvals)[0],1))
xy_vals = np.append(xr,yr,1)
xyt = tinv.transform(xy_vals)
xt, yt = xyt[:, 0], xyt[:, 1]
d = np.hypot(xt - event.x, yt - event.y)
indseq, = np.nonzero(d == d.min())
ind = indseq[0] #print(d[ind])
if d[ind] >= epsilon:
ind = None #print(ind)
return ind def motion_notify_callback(event):
'on mouse movement'
global yvals
if pind is None:
return
if event.inaxes is None:
return
if event.button != 1:
return #update yvals
#print('motion x: {0}; y: {1}'.format(event.xdata,event.ydata))
yvals[pind] = np.clip(event.ydata,-1,1) # update curve via sliders and draw
sliders[pind].set_val(yvals[pind])
fig.canvas.draw_idle() ############################ ed = st+pd.Timedelta(days=N-1)
datelst = pd.date_range(st,ed) # ax1.plot () ########################### X = np.arange(0,xmax+1,0.1)
ax1.plot (X, func(X), 'k--', label='original')
l, = ax1.plot (x,yvals,color='k',linestyle='none',marker='o',markersize=8)
m, = ax1.plot (X, spline(X), 'r-', label='spline') ax1.set_yscale('linear')
ax1.set_xlim(0, 32)
ax1.set_ylim(-1.05,1.05)
ax1.set_xlabel('dt')
ax1.set_ylabel('p')
ax1.grid(True)
ax1.yaxis.grid(True,which='minor',linestyle='--')
ax1.legend(loc=2,prop={'size':8}) sliders = []
for i in np.arange(N): axamp = plt.axes([0.84, 0.95-(i*0.03), 0.12, 0.02])
# Slider
date_i = datelst[i]
mth = date_i.month
day = date_i.day
s = Slider(axamp, '{}/{}'.format(mth,day), -1, 1, valinit=yvals[i])
sliders.append(s) for i in np.arange(N):
#samp.on_changed(update_slider)
sliders[i].on_changed(update) axres = plt.axes([0.84, 0.95-((N)*0.03), 0.06, 0.02])
bres = Button(axres, 'Reset')
bres.on_clicked(reset) axres = plt.axes([0.84+0.08, 0.95-((N)*0.03), 0.06, 0.02])
bres2 = Button(axres, 'Save')
bres2.on_clicked(save_p) fig.canvas.mpl_connect('button_press_event', button_press_callback)
fig.canvas.mpl_connect('button_release_event', button_release_callback)
fig.canvas.mpl_connect('motion_notify_event', motion_notify_callback) plt.show()
Python 使用Matplotlib绘制可拖动的折线的更多相关文章
- Python——使用matplotlib绘制柱状图
Python——使用matplotlib绘制柱状图 1.基本柱状图 首先要安装matplotlib(http://matplotlib.org/api/pyplot_api.htm ...
- python使用matplotlib绘制折线图教程
Matplotlib是一个Python工具箱,用于科学计算的数据可视化.借助它,Python可以绘制如Matlab和Octave多种多样的数据图形.下面这篇文章主要介绍了python使用matplot ...
- Python使用matplotlib绘制三维曲线
本文主要演示如何使用matplotlib绘制三维图形 代码如下: # -*- coding: UTF-8 -*- import matplotlib as mpl from mpl_toolkits. ...
- python包matplotlib绘制图像
使用matplotlib绘制图像 import matplotlib.pyplot as plt from matplotlib.pyplot import MultipleLocator impor ...
- 【Python】matplotlib绘制折线图
一.绘制简单的折线图 import matplotlib.pyplot as plt squares=[1,4,9,16,25] plt.plot(squares) plt.show() 我们首先导入 ...
- Python 使用 matplotlib绘制3D图形
3D图形在数据分析.数据建模.图形和图像处理等领域中都有着广泛的应用,下面将给大家介绍一下如何在Python中使用 matplotlib进行3D图形的绘制,包括3D散点.3D表面.3D轮廓.3D直线( ...
- Python:matplotlib绘制线条图
线型图是学习matplotlib绘图的最基础案例.我们来看看具体过程: 下面我们将两条曲线绘制到一个图形里: 可以看到这种方式下,两个线条共用一个坐标轴,并且自动区分颜色. plot方法的核心是 ...
- 广义mandelbrot集,使用python的matplotlib绘制,支持放大缩小
迭代公式的指数,使用的1+5j,这是个复数.所以是广义mandelbrot集,大家能够自行改动指数,得到其它图形.各种库安装不全的,自行想办法,能够在这个站点找到差点儿全部的python库 http: ...
- Python:matplotlib绘制直方图
使用hist方法来绘制直方图: 绘制直方图,最主要的是一个数据集data和需要划分的区间数量bins,另外你也可以设置一些颜色.类型参数: plt.hist(np.random.randn(1 ...
- Python:matplotlib绘制散点图
与线型图类似的是,散点图也是一个个点集构成的.但不同之处在于,散点图的各点之间不会按照前后关系以线条连接起来. 用plt.plot画散点图 奇怪,代码和前面的例子差不多,为什么这里显示的却是散 ...
随机推荐
- C语言结构体的内存分配
一.结构体内存分配原则 原则一:结构体中元素按照定义顺序存放到内存中,但并不是紧密排列.从结构体存储的首地址开始 ,每一个元素存入内存中时,它都会认为内存是以自己的宽度来划分空间的,因此元素存放的位置 ...
- C++里也有菱形运算符?
最近在翻<c++函数式编程>的时候看到有一小节在说c++14新增了"菱形运算符".我寻思c++里好像没什么运算符叫这名字啊,而且c++14新增的功能很少,我也不记得有添 ...
- 在网页上直接运行Win11,5秒内用AI克隆自己的声音 | 蛮三刀酱的Github周刊第二期
大家好,这里是每周更新的Github精彩分享周刊,我是每周都在搬砖的蛮三刀酱. 我会从Github热门趋势榜里选出 高质量.有趣,牛B 的开源项目进行分享. 1. PowerShell:不止于Wind ...
- 记录几十页html生成pdf的历程和坑(已用bookjs-easy解决)(生成、转换、拼接pdf)
懒得看的朋友,先说最终解决办法,主力为 前端依靠插件 bookjs-easy(点击直接跳转官网)并跳转到下面的第三点查看 接下来详细记录下整个试探的方向和历程 项目需求:是生成一个页数达到大几十页的p ...
- ansible(3)--ansible的相关命令行工具
目录 1 ansible命令详解 2 ansible-doc显示模块帮助信息 3 ansible-playbook 4 ansible-galaxy 5 ansible-console 1 ansib ...
- get pull报错 Please commit your changes or stash them before you merge
当本地分支和远程修改了同一个文件代码,pull远程分支的代码的时候会出现文件冲突 出现这个错误 Please commit your changes or stash them before you ...
- 得物 ZooKeeper SLA 也可以 99.99%
1. 背景 ZooKeeper(ZK)是一个诞生于 2007 年的分布式应用程序协调服务.尽管出于一些特殊的历史原因,许多业务场景仍然不得不依赖它.比如,Kafka.任务调度等.特别是在 Flink ...
- PCF 的 Npcf_PolicyAuthorization 服务化接口
目录 文章目录 目录 引用 前文列表 术语 PCF Npcf_PolicyAuthorization 服务化操作类型 服务化接口参数类型 创建 Application Session Context: ...
- 基于webapi的websocket聊天室(二)
上一篇 - 基于webapi的websocket聊天室(一) 消息超传缓冲区的问题 在上一篇中我们定义了一个聊天室WebSocketChatRoom.但是每个游客只分配了400个字节的发言缓冲区,大概 ...
- 用STM32F4的DMA实现高速、实时的同步并行通信——以读取高速ADC为例[原创www.cnblogs.com/helesheng]
大概6-7年前,在网上看到过一篇用STM32F1的DMA控制GPIO输出高速数字波形的帖子.觉得很有意思,就自己试了试:控制GPIO输出波形翻转的速度最高只能达到3-4MHz,且容易受到STM32F1 ...