技术标签: python matplotlib 圆锥曲线 动图 # Python可视化 animation
源码地址:Python动态绘制圆锥曲线,并封装成类
后续:Python高级动态绘图系统:复杂曲线的轨迹演示
无论从什么角度来说,圆锥曲线都非常适合动态演示,尤其是其中优美的几何关系,更能在动态变化中得到淋漓尽致的表现。三种圆锥曲线的方程分别如下
椭圆 | 双曲线 | 抛物线 |
---|---|---|
x 2 a + y 2 b = 1 \frac{x^2}{a}+\frac{y^2}{b}=1 ax2+by2=1 | x 2 a − y 2 b = 1 \frac{x^2}{a}-\frac{y^2}{b}=1 ax2−by2=1 | y 2 = 2 p x y^2=2px y2=2px |
在Python中,绘制动图需要用到matplotlib
中的animation
包,其调用方法以及接下来要用到的参数为
ani = animation.FuncAnimation(fig, func, frames, interval)
其中fig
为绘图窗口,func
为绘图函数,其返回值为图像,frames
为迭代参数,如果为整型的话,其迭代参数则为range(frames)
。
为了绘图方便,故将椭圆写为参数方程
{ x = a cos t y = b sin t \left\{ \begin{aligned} x = a\cos t\\ y = b\sin t \end{aligned}\right. { x=acosty=bsint
设 a = 5 , b = 3 , c = 4 a=5,b=3,c=4 a=5,b=3,c=4,则焦点为 ( 4 , 0 ) , ( − 4 , 0 ) (4,0),(-4,0) (4,0),(−4,0),则有
这个代码其实很久以前就写过,在这片博客里:Python绘制动态的圆锥曲线,这回再重新抄写一遍:
# 这三个包在后面的程序中不再复述
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
a,b,c = 5,3,4
fig = plt.figure(figsize=(12,9))
ax = fig.add_subplot(autoscale_on=False,
xlim=(-a,a),ylim=(-b,b))
ax.grid()
line, = ax.plot([],[],'o-',lw=2)
trace, = ax.plot([],[],'-', lw=1)
theta_text = ax.text(0.02,0.85,'',transform=ax.transAxes)
textTemplate = '''theta = %.1f°\n
lenL = %.1f, lenR = %.1f\n
lenL+lenR = %.1f'''
xs,ys = [], []
def animate(i):
if(i==0):
xs.clear()
ys.clear()
theta = i*0.04
x = a*np.cos(theta)
y = b*np.sin(theta)
xs.append(x)
ys.append(y)
line.set_data([-c,x,c], [0,y,0])
trace.set_data(xs,ys)
lenL = np.sqrt((x+c)**2+y**2)
lenR = np.sqrt((x-c)**2+y**2)
theta_text.set_text(textTemplate %
(180*theta/np.pi, lenL, lenR, lenL+lenR))
return line, trace, theta_text
ani = animation.FuncAnimation(fig, animate, 157,
interval=5, blit=True)
ani.save("ellipse.gif")
plt.show()
其实可以看到,这个程序虽然完成了画图的任务,但并不好看,一个重要的原因是全局变量参与到了核心的动图绘制中,让人感到十分不舒服。而且代码复用率太低,也就只能画个椭圆了,再画个其他的东西都是有心无力的。
经过观察可以发现,除了animate
函数之外,其他的代码负责绘图逻辑,应该不必做出太大的更改。
仔细考察被画的图形,大概可分为两类,其一是椭圆的生成曲线,这部分曲线从无到有,累积生成;另一部分则是过焦点的两条线段,它们的位置实时变化。所以,在生成动态图像时,需要至少两个函数。
接下来,把握这条规律,可将其写成类。
a,b,c = 5,3,4
def traceFunc(theta):
x = a*np.cos(theta)
y = b*np.sin(theta)
return x,y
def lineFunc(x,y):
return [-c,x,c], [0,y,0]
def txtFunc(theta):
th = 180*theta/np.pi
x,y = traceFunc(theta)
lenL = np.sqrt((x+c)**2+y**2)
lenR = np.sqrt((x-c)**2+y**2)
txt = f'theta={
th:.2f}\nlenL={
lenL:.2f},lenR={
lenR:.2f}\n'
txt += f'lenL+lenR={
lenL+lenR:.2f}'
return txt
xlim,ylim = (-a,a), (-b,b)
ts = np.linspace(0,6.28,200)
class drawAni():
# func为参数方程
def __init__(self,lineFunc,traceFunc,txtFunc,
ts,xlim,ylim,figsize=(16,9)):
self.lineFunc = lineFunc
self.traceFunc = traceFunc
self.txtFunc = txtFunc
self.fig = plt.figure(figsize=figsize)
ax = self.fig.add_subplot(autoscale_on=False,
xlim=xlim,ylim=ylim)
ax.grid()
self.line, = ax.plot([],[],'o-',lw=2)
self.trace, = ax.plot([],[],'-',lw=1)
self.text = ax.text(0.02,0.85,'',transform=ax.transAxes)
self.xs, self.ys, self.ts = [],[],ts
self.run(ts)
def animate(self,t):
if(t==self.ts[0]):
self.xs, self.ys = [],[]
x,y = self.traceFunc(t)
self.xs.append(x)
self.ys.append(y)
self.line.set_data(self.lineFunc(x,y))
self.trace.set_data(self.xs,self.ys)
self.text.set_text(self.txtFunc(t))
return self.line, self.trace, self.text
def run(self,ts):
self.ani = animation.FuncAnimation(self.fig, self.animate, ts, interval=5, blit=True)
plt.subplots_adjust(left=0.05, right=0.95, top=0.95, bottom=0.05)
plt.show()
def save(self,saveName):
self.ani.save(saveName)
在导入之后,可直接写为
an = drawAni(lineFunc, traceFunc, txtFunc, ts, xlim, ylim, (12,9))
an.save("test.gif")
同样可以得到椭圆曲线的生成过程。
双曲线的参数方程为
{ x = a ch t = e t + e − t 2 y = b sh t = e t − e − t 2 \left\{\begin{aligned} x = a\ch t=\frac{e^t+e^{-t}}{2}\\ y = b\sh t=\frac{e^t-e^{-t}}{2} \end{aligned}\right. ⎩⎪⎪⎨⎪⎪⎧x=acht=2et+e−ty=bsht=2et−e−t
设 a = 4 , b = 2 a=4,b=2 a=4,b=2,则其效果为
代码如下
a,b = 4,2
c = np.sqrt(a**2+b**2)
def traceFunc(t):
return a*np.cosh(t), b*np.sinh(t)
def lineFunc(x,y):
return [-c,x,c], [0,y,0]
def txtFunc(theta):
th = 180*theta/np.pi
x,y = traceFunc(theta)
lenL = np.sqrt((x+c)**2+y**2)
lenR = np.sqrt((x-c)**2+y**2)
txt = f'theta={
th:.1f}\nlenL={
lenL:.1f},lenR={
lenR:.1f}\n'
txt += f'lenL-lenR={
lenL-lenR:.2f}'
return txt
xlim,ylim = (-7,25), (-12,12)
ts = np.arange(-3,3,0.05)
an = drawAni(lineFunc, traceFunc, txtFunc, ts, xlim, ylim,(12,9))
an.save("hyperbola.gif")
这时,封装成类的优势就凸显出来了,和之前的那篇博文相比,的确只需改动最核心的轨迹生成部分,而无需更改其绘图代码。
令 p = 1 p=1 p=1,则焦点位置为 ( 0 , p 2 ) (0,\frac{p}{2}) (0,2p),准线为 x = − p 2 x=-\frac{p}{2} x=−2p,代码如下
p = 1
def traceFunc(y):
return y**2/p/2, y
def lineFunc(x,y):
return [-p/2,x,p/2], [y,y,0]
def txtFunc(theta):
th = 180*theta/np.pi
x,y = traceFunc(theta)
lenL = x+p/2
lenF = np.sqrt((x-p/2)**2+y**2)
txt = f'y={
y:.1f}\nlenL={
lenL:.1f},lenF={
lenF:.1f}\n'
txt += f'lenL-lenF={
lenL-lenF:.1f}'
return txt
xlim,ylim=(-0.6,4.5),(-3,3)
ys = np.arange(-3,3,0.1)
an = drawAni(lineFunc, traceFunc, txtFunc, ys, xlim, ylim,(12,8))
an.save("parabola.gif")
这张图看上去稍微有些别扭,主要是因为缺少一个极轴,由于极轴永远是固定的,所以为绘图函数添加一个固定的直线,对此,只需添加一个初始化函数即可
def initFunc(ax):
ax.plot([-p,-p],[-3,3],'-',lw=1)
class drawAni():
# func为参数方程
def __init__(self,lineFunc,traceFunc,txtFunc,
ts,xlim,ylim,figsize=(16,9),iniFunc=None):
#省略
ax = self.fig.add_subplot(autoscale_on=False,
xlim=xlim,ylim=ylim)
ax.grid()
if iniFunc: initFunc(ax)
#省略
然后绘图
an = drawAni(lineFunc, traceFunc, txtFunc, ys, xlim, ylim,(12,8),initFunc)
an.save("parabola.gif")
这回味就对了。
文章浏览阅读8.3k次,点赞2次,收藏6次。VUE定义数组传递后台,总是接收不到,需要格式化成json传递才行,我这是一个案例,可以根据需求灵活转换前台代码: data(){ return{ title:'', idd:'1', testArry:[1,3,4,4,5], datacontent:'' } },let formData = new FormData..._vue el-upload 批量上传,后端接收不到数组
文章浏览阅读5.6k次。直接上方法:file --》setting--》Editor--》File Types --》ActionScript - -》Ignore files and folders --》想要过滤掉的文件类型后缀。例如想要过滤掉后缀为.iml的文件,就添加 *.iml; 后续通过idea提交代码时,就自动过滤掉后缀为.iml的文件。..._idea 过滤iml
文章浏览阅读464次。Ubuntu 16.04 安装Maven3.5.21 下载地址http://maven.apache.org/download.cgi2 将下载到的apache-maven-3.5.2-bin.tar.gz文件上传到/temp目录下,然后切换到root用户下,执行如下命令。root@test:/temp# tar zxvf apache-maven-3.5.2-bin.tar.gzroot@te..._ubuntumaven-3.5.2-bin.tar.gz
文章浏览阅读8.5k次,点赞2次,收藏7次。Ubuntu阿里源镜像_ubuntu阿里云镜像源
文章浏览阅读1.1k次。Litos这篇文章主要描述我们如何在litos工程中,自定义一个demo出来。文章目录Litos前言一、前期准备二、使用步骤1.查看其它demos文件2.修改上层目录的Kconfig和mk3.执行make menuconfig选择库和新加demo4.修改cjson_demo.c和.h文件5.修改demo_entry.c文件6.执行Make编译7.程序运行现象前言1.环境及MCU 小熊派(IOT开发板)+linux环境+litos提示:以下是本篇文章正文内容,下面案例可供参考一、前期准备1_liteos增加自定义的系统调用
文章浏览阅读348次。排序检索、过滤数据:IN操作符、NOT操作符、LIKE操作符、创建计算字段、函数处理、汇总数据、分组数据、子查询、联结表、高级联结、组合查询、视图、游标、唯一约束、触发器_nosql where百分号用法
文章浏览阅读2.2k次,点赞4次,收藏7次。点击上方“Java之间”,选择“置顶或者星标”你关注的就是我关心的!来源:开源最前线(ID:OpenSourceTop)上一篇:IDEA 插件推荐: EasyCode一键生成所需代码~..._github东北话编程
文章浏览阅读202次,点赞8次,收藏4次。多组数据,每组数据有三行,第一行为序列A和B的长度n和m,第二行为序列A的n个元素,第三行为序列B的m个元素(元素之间用空格分隔)。n=0且m=0时输入结束。本关任务:给定两个非递减的整数序列A和B,利用链表表示序列A和B,将A和B合并为一个非递增的有序序列C,序列C允许有重复的数据。要求空间复杂度为O(1)。对于每组数据输出一行,为合并后的序列,每个数据之间用空格分隔。
文章浏览阅读1k次。Ubuntu Texlive TeXstudio Tikz 安装与环境配置https://blog.csdn.net/williamyi96/article/details/90732304_texstudio tikzp
文章浏览阅读6.5k次,点赞6次,收藏28次。举例求下面矩阵的四连通域(3)[1100010100011000001000001] \left[ \begin{matrix} 1 & 1 & 0 & 0 & 0 \\ 1 & 0 & 1 & 0 & 0 \\ 0 & 1 &a..._01矩阵求连通域
文章浏览阅读2k次。service 的 clusterIP,这个所谓的 虚地址, 其实是若干条iptables规则:<pre>-A KUBE-SERVICES -d 10.11.97.177/32 -p tcp -m comment --comment "default/my-nginx: cluster IP&am..._kubernets curl svc cluster-ip
文章浏览阅读851次,点赞18次,收藏16次。1 简介今天学长向大家介绍一个机器视觉的毕设项目,基于深度学习的人体目标检测算法研究与实现毕业设计 深度学习行人目标检测系统。