用Python绘制一个运动在二维函数上的动点(使用matplotlib.animation) |
您所在的位置:网站首页 › 直线运动怎么画图像的 › 用Python绘制一个运动在二维函数上的动点(使用matplotlib.animation) |
文章目录
1、代码2、结果3、加入带文本标签的代码4、结果5、解决两个函数中动点如何运动的问题6、结果
1、代码
使用Python中的matplotlib.animation库进行动点的绘制。 可以从官网进行学习,里面有很多有意思的动图绘制。matplotlib官网~ import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation fig, ax = plt.subplots() x = np.arange(0, 2*np.pi, 0.1) line, = ax.plot(x, np.sin(x)) def animate(i): # update the data. # 如果你打印一下i,就能明白为什么要设置为2 if len(ax.lines) == 2: ax.lines.pop(1) ax.plot(x[i], np.sin(x)[i], 'o', color='red') return line, ax ani = animation.FuncAnimation( fig, animate, frames=x.size, interval=100, blit=False, save_count=50) plt.show() 2、结果本次编写的目的是为了测试一下群体智能算法的优化策略。会不定期会更新,优化或添加解析。 ![]() ———————————————————————————更新——————————————————————————— 3、加入带文本标签的代码 import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation # 不得转载 fig, ax = plt.subplots() x = np.arange(0, 2*np.pi, 0.1) line, = ax.plot(x, np.sin(x)) def animate(i): # update the data. # 如果你打印一下i,就能明白为什么要设置为2 if len(ax.lines) == 2: ax.lines.pop(1) # List 的 pop 方法默认删除最后一个元素, 但是我们要删除的是上一个存在的 if len(ax.texts) > 0: ax.texts.pop(0) ax.plot(x[i], np.sin(x)[i], 'o', color='red') ax.text(x[i], np.sin(x)[i], ' ('+str(round(x[i], 2))+','+str(round(np.sin(x)[i], 2))+'+)', fontsize=10) return line, ax ani = animation.FuncAnimation( fig, animate, frames=x.size, interval=500, blit=False, save_count=50) plt.show() 4、结果![]() |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |