编程开源技术交流,分享技术与知识

网站首页 > 开源技术 正文

Python动态绘图的方法

wxchong 2024-11-17 16:46:48 开源技术 21 ℃ 0 评论

方法一:matplotlib循环添加数据

import numpy as np
import matplotlib.pyplot as plt
"""
动态绘图方法一:
通过刷新图面的方法,每次循环在绘制新图画前,把当前绘图区的内容进行清空,
然后绘制新的图形
"""
fig=plt.figure() #设置图面大小
plt1=plt.subplot(211) #设置绘图区域2行1列,第一个图区
plt2=plt.subplot(212)#设置绘图区域2行1列,第二个图区
plt1.axis([0, 100, 0, 1])
xa=[]
ya = []
pause_time=0.01 #动态刷新时间
for i in range(50):
y = np.random.random()
ya.append(y) # 每迭代一次,将i放入y1中画出来
xa.append(i)
plt1.cla() # 清除键
plt1.plot(xa,ya)
plt.pause(pause_time)

方法二:matplotlib循环刷新-清除旧数据-添加新数据

"""
利用绘图的特性,每次绘制的内容,在前一次的结果上添加,
这个方法需要对数据进行特殊处理,每次绘制的数据,只有新添加的数据,旧的数据需要删除
"""
plt2.axis([0, 100, 0, 1])
xs = [0, 0]
ys = [1, 1]
for i in range(50):
y = np.random.random()
xs[0] = xs[1]
ys[0] = ys[1]
xs[1] = i
ys[1] = y
plt2.plot(xs, ys)
plt.pause(pause_time)
plt.show()

方法三、利用第三方插件imagemagick实现动态图保存gif文件

1.首先现在imagemagick软件,这里有个坑,需要下载6.9版本的,应为7.0版本没有了convert.exe命令,必须用6.9版本的,网上的教程都是用的这个convert命令

2.安装完,imagemagick后,matplotlib并不知道这个命令所在的位置,因此需要告诉命令convert的绝对位置

在python中利用print(matplotlib.matplotlib_fname()),获得matplotlib配置文件的位置,在最后一行,修改命令的全局路径,为animation.convert_path: D:\Program Files\ImageMagick-6.9.10-Q16\convert.exe

3.在程序中就可以正常使用了

import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.animation as animation
print(matplotlib.matplotlib_fname()) # 修改matplotlib配置文件的位置
fig = plt.figure() # 画纸
ax = plt.subplot() # 绘图区
xdata, ydata = [], [] # x,y轴数据数组
ln, = plt.plot([], [], 'r', animated=True) #
def init():
ax.set_xlim(0, 100)
ax.set_ylim(0, 1)
return ln,
def update(frame): #frame的数据来自FuncAnimation函数frams的内容,每次调用函数,区frames中的一个数据
xdata.append(frame)
# print(frame)
ydata.append(np.random.random())
ln.set_data(xdata, ydata) #在ln中添加数据
return ln,
anim = animation.FuncAnimation(fig, update, frames=range(10,60), interval=10, init_func=init, blit=True, repeat=False)
# anim.save('sinx.gif', writer='imagemagick') #存储为gif文件
# anim.save('sinx2.html') #利用默认的工具,存储为html文件
plt.show()

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表