为了提出这个问题,我清理了我的代码,然后在清理的同时找到了解决方案。请参阅下面我的解决方案。在
我试图在imshow()
中创建一个动态图像(一部电影),上面用matplotlib.patches
绘制静态圆圈,但随着电影播放,它的速度变慢了(延迟随着时间线性增加)。这些圆是静态的,因此必须有一种方法使matplotlib.patches
在imshow()
更新时运行得更快。这是我的代码:
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import Circle
from scipy.linalg import toeplitz
# Radius for circle of circles
r = 0.5
# Number of circles
n = 7
# Locations of centers of circles
a = r*np.transpose(np.array([np.cos(np.arange(0,2*np.pi,2*np.pi/n)),
np.sin(np.arange(0,2*np.pi,2*np.pi/n))]))
# Create first background image.
E = toeplitz(np.random.rand(70))
# Plot the first frame.
fig = plt.figure(1)
ax = fig.add_subplot(111)
im = ax.imshow(E,extent=np.array([-1,1,-1,1]))
# Draw the circles on the image
for k in range(np.shape(a)[0]):
ax.add_patch(Circle((a[k][0],a[k][1]),0.1))
plt.show()
# Update with background image and redraw the circles.
for t in range(60):
# Update the background image.
E=toeplitz(np.random.rand(70))
im.set_array(E)
# Update the circles
for k in range(np.shape(a)[0]):
ax.add_patch(Circle((a[k][0],a[k][1]),0.1))
fig.canvas.draw()
结果证明这是一个非常简单的解决方案。
add_patch()
函数只需在电影开始时运行一次,set_array
会更新圆后面的数组。以下是从主for
循环中删除add_patch()
函数的代码:这几乎以恒定的时间运行。希望这能为其他人节省几小时的调试时间。在
相关问题 更多 >
编程相关推荐