2017-09-22 31 views
0

我想在車輛移動時在背景中顯示地圖。我正在使用matplotlib動畫功能。運動看起來很好。但我在加載地圖時嘗試了以下內容。地圖未加載。只有黑色補丁可見。我也試着指定zorder。但沒有用。在matplotlib動畫背景中顯示地圖

ani = animation.FuncAnimation(fig, animate, len(x11),interval=150, 
          blit=True, init_func=init, repeat=False) 

img = cbook.get_sample_data('..\\maps.png') 
image = plt.imread(img) 
plt.imshow(image) 
plt.show() 

回答

1

您可以閱讀scipy.misc import imread背景圖像和使用plt.imshow動畫中的背景來呈現。

下面的例子會生成一個圓圈(我們假設它的汽車),將「usa_map.jpg」放在背景中,然後在地圖上移動圓圈。

獎金,你可以作爲一個電影mp4格式,採用使用編碼器保存動畫如ffmpeganim.save('the_movie.mp4', writer = 'ffmpeg', fps=30)

源代碼

import numpy as np 
import matplotlib.pyplot as plt 
import matplotlib.image as mpimg 
import matplotlib.animation as animation 
from scipy.misc import imread 


img = imread("usa_map.jpg") 

fig = plt.figure() 
fig.set_dpi(100) 
fig.set_size_inches(7, 6.5) 

ax = plt.axes(xlim=(0, 20), ylim=(0, 20)) 
patch = plt.Circle((5, -5), 0.75, fc='y') 


def init(): 
    patch.center = (20, 20) 
    ax.add_patch(patch) 
    return patch, 

def animate(i): 
    x, y = patch.center 
    x = 10 + 3 * np.sin(np.radians(i)) 
    y = 10 + 3 * np.cos(np.radians(i)) 
    patch.center = (x, y) 
    return patch, 

anim = animation.FuncAnimation(fig, animate, 
           init_func=init, 
           frames=360, 
           interval=20, 
           blit=True) 

plt.imshow(img,zorder=0, extent=[0.1, 20.0, 0.1, 20.0]) 
anim.save('the_movie.mp4', writer = 'ffmpeg', fps=30) 
plt.show() 

上面的代碼會產生一個圓圈圍繞美國移動animaton地圖。它也將被保存爲'the_movie.mp4',我不能在這裏上傳。

結果圖像
enter image description here

+0

感謝。它很好地工作 – narasimman

+0

很高興知道它解決了這個問題。投票表示讚賞。 –