gpt4 book ai didi

python - 提高在 matplotlib 中重绘等高线图的速度

转载 作者:太空宇宙 更新时间:2023-11-03 13:34:06 25 4
gpt4 key购买 nike

我有一个 python 程序,可以将文件中的数据绘制为该文本文件中每一行的等高线图。目前,我的界面中有 3 个独立的等高线图。无论我是从文件中读取数据还是在执行脚本之前将其加载到内存中都没有关系,我只能从等高线图中获得 ~6fps。

我也试过只使用一个轮廓和其余的正常图,但速度只增加到 7fps。我不相信画几条线会在计算上如此费力。有没有办法让它更快?理想情况下,获得至少 30fps 会很好。

我绘制轮廓的方式是,对于我的数据的每一行,我都会删除前一行:

for coll in my_contour[0].collections:
coll.remove()

并添加一个新的

my_contour[0] = ax[0].contour(x, y, my_func, [0])

在代码的开头,我有 plt.ion() 来更新我添加的绘图。

如有任何帮助,我们将不胜感激。

谢谢

最佳答案

这是一个关于如何在动画中使用 contour 绘图的示例。它使用 matplotlib.animation.FuncAnimation 可以轻松打开和关闭 blitting。使用 blit=True,它在我的机器上以 ~64 fps 的速度运行,而不会 blitting ~55 fps。请注意,interval 当然必须允许快速动画;将它设置为 interval=10(毫秒)将允许高达 100 fps,但绘图时间将它限制为比这慢的东西。

import matplotlib.pyplot as plt
import matplotlib.animation
import numpy as np
import time

x= np.linspace(0,3*np.pi)
X,Y = np.meshgrid(x,x)
f = lambda x,y, alpha, beta :(np.sin(X+alpha)+np.sin(Y*(1+np.sin(beta)*.4)+alpha))**2
alpha=np.linspace(0, 2*np.pi, num=34)
levels= 10
cmap=plt.cm.magma


fig, ax=plt.subplots()
props = dict(boxstyle='round', facecolor='wheat')
timelabel = ax.text(0.9,0.9, "", transform=ax.transAxes, ha="right", bbox=props)
t = np.ones(10)*time.time()
p = [ax.contour(X,Y,f(X,Y,0,0), levels, cmap=cmap ) ]

def update(i):
for tp in p[0].collections:
tp.remove()
p[0] = ax.contour(X,Y,f(X,Y,alpha[i],alpha[i]), levels, cmap= cmap)
t[1:] = t[0:-1]
t[0] = time.time()
timelabel.set_text("{:.3f} fps".format(-1./np.diff(t).mean()))
return p[0].collections+[timelabel]

ani = matplotlib.animation.FuncAnimation(fig, update, frames=len(alpha),
interval=10, blit=True, repeat=True)
plt.show()

enter image description here

请注意,在上面的动画 gif 中显示的帧速率较慢,因为保存图像的过程需要更长的时间。

关于python - 提高在 matplotlib 中重绘等高线图的速度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42386372/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com