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画散点图 奇怪,代码和前面的例子差不多,为什么这里显示的却是散 ...
随机推荐
- FFmpeg开发笔记(十七)Windows环境给FFmpeg集成字幕库libass
libass是一个适用于ASS和SSA格式(Advanced Substation Alpha/Substation Alpha)的字幕渲染器,支持的字幕类型包括srt.ass等,凡是涉及到给视频画 ...
- hbuilder打包报错:java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 7 column 15 path $.icons
一个棘手的问题,在网上找几乎没有出现这样的案例,个别也只有翻译没有解决方式,,,,,自己研究一番发现这实际上都不算是个问题 这句话翻译:这个位置应该是个对象而不是数组,解决方法: 在manifest. ...
- 二:大数据架构回顾-Kappa架构
Kappa 架构是由 LinkedIn 的前首席工程师杰伊·克雷普斯(Jay Kreps)提出的一种架构思想.克雷普斯是几个著名开源项目(包括 Apache Kafka 和 Apache Samza ...
- 【爬虫+情感判定+Top10高频词+词云图】"乌克兰"油管热评python舆情分析
目录 一.分析背景 二.整体思路 三.代码讲解 3.1 爬虫采集 3.2 情感判定 3.3 Top10高频词 3.4 词云图 四.得出结论 五.同步视频演示 六.附完整源码 一.分析背景 乌克兰局势这 ...
- Rust 错误处理
rust 处理错误,不使用 try catch, 而是使用 Result<T, E>. 简单的处理rust错误 在各种关于rust错误处理的文档中,为了解释清楚其背后的机制,看着内容很多, ...
- three.js介绍和学习资料说明
1.three.js能做什么 Three.js是基于原生WebGL封装运行的三维引擎,在所有WebGL引擎中,Three.js是国内文资料最多.使用最广泛的三维引擎.既然Threejs是一款WebGL ...
- AIRIOT答疑第5期|如何使用低代码业务流引擎?
推拉拽! AIRIOT平台业务流引擎可创建丰富的业务流程,实现从流程定义.数据处理.任务工单.消息通知.日志追踪的闭环流转.多类型节点任意组合,可视化流程日志,精准追踪流程流转.人工任务统一管理,审批 ...
- QtCreator 跨平台开发添加动态库教程(以OpenCV库举例)- Windows篇
Qt具有跨平台的特性,即Qt数据结构与算法库本身跨平台和编译脚本(.pro)跨平台.在同时具有Windows下和Linux开发的需求时,最好的建议是使用QtCreator来开发,虽然也可以使用其他 ...
- 云原生时代的"应用级"多云管理
作者:张齐 当前云计算有多种形态公有云.私有云.边缘云.虚拟机等,如何高效管理多云是当前面临的问题,在云原生时代,又该如何利用云原生技术实现多云管理?本文将讲解通过 Rainbond实现"应 ...
- k8s组件和网络插件挂掉,演示已有的pod是否正常运行
环境 03 master ,05 06是node [root@mcwk8s03 mcwtest]# kubectl get nodes -o wide NAME STATUS ROLES AGE VE ...