Python打造动态绘图系统

Python打造动态绘图系统,第1张

文章目录
    • 椭圆
    • 绘图系统
    • 绘制双曲线
    • 抛物线

源码地址: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 ax2by2=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) (40),(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+ety=bsht=2etet

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")


这回味就对了。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/790589.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-05
下一篇 2022-05-05

发表评论

登录后才能评论

评论列表(0条)

保存