python plt修改绘图区大小_Python动态绘图的方法

2022-10-07 11:27:45

方法一:matplotlib循环添加数据

importnumpyasnpimportmatplotlib.pyplotasplt"""
动态绘图方法一:
通过刷新图面的方法,每次循环在绘制新图画前,把当前绘图区的内容进行清空,
然后绘制新的图形
"""
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 #动态刷新时间foriinrange(50):
y = np.random.random()
ya.append(y) # 每迭代一次,将i放入y1中画出来
xa.append(i)
plt1.cla() # 清除键
plt1.plot(xa,ya)
plt.pause(pause_time)

25af44911568b69403e9ddf963ab7886.png

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

"""
利用绘图的特性,每次绘制的内容,在前一次的结果上添加,
这个方法需要对数据进行特殊处理,每次绘制的数据,只有新添加的数据,旧的数据需要删除
"""
plt2.axis([0, 100, 0, 1])
xs = [0, 0]
ys = [1, 1]foriinrange(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()

860b5f7d9f6cea6b88c5e3d502d1f68d.png

方法三、利用第三方插件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 FilesImageMagick-6.9.10-Q16convert.exe

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

importnumpyasnpimportmatplotlibimportmatplotlib.pyplotaspltimportmatplotlib.animationasanimation
print(matplotlib.matplotlib_fname()) # 修改matplotlib配置文件的位置
fig = plt.figure() # 画纸
ax = plt.subplot() # 绘图区
xdata, ydata = [], [] # x,y轴数据数组
ln, = plt.plot([], [],'r', animated=True) #definit():
ax.set_xlim(0, 100)
ax.set_ylim(0, 1)returnln,defupdate(frame): #frame的数据来自FuncAnimation函数frams的内容,每次调用函数,区frames中的一个数据
xdata.append(frame)
# print(frame)
ydata.append(np.random.random())
ln.set_data(xdata, ydata) #在ln中添加数据returnln,
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()

1a1f3515e51bded679c0a43eed3679a8.png
  • 作者:weixin_39625586
  • 原文链接:https://blog.csdn.net/weixin_39625586/article/details/113312602
    更新时间:2022-10-07 11:27:45