2017-05-08 57 views
0

我清理了我的代碼以問這個問題,然後在清理時找到了解決方案。請參閱下面的解決方案動態圖像使用imshow()和matplotlib.patches快速靜態圓圈

我想用matplotlib.patchesimshow()上創建一個動態圖像(電影),其頂部使用靜態圓圈繪製,但隨着電影播放(延遲隨時間線性增加)而減慢。圓圈是靜態的,因此必須有一種方法使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() 

回答

0

這原來是一個非常簡單的解決方案。 add_patch()函數只需要在影片開頭運行一次,並且set_array更新圓圈後面​​的數組。下面是與add_patch()功能從主for循環中去除代碼:

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. 
for t in range(60): 
    E=toeplitz(np.random.rand(70)) 
    im.set_array(E) 
    fig.canvas.draw() 

這與運行幾乎恆定時間。希望這將在未來爲其他人節省幾個小時的時間。