使用matplotlib动画在后台显示地图 [英] displaying a map in the background with matplotlib animation
问题描述
我想在车辆行驶时在后台显示地图.我正在使用 matplotlib 动画函数.运动看起来不错.但是我在加载地图时尝试了以下方法.地图未加载.只有一个黑色补丁是可见的.我也尝试指定zorder.但什么都行不通.
I want to show a map in the background when a vehicle is moving. I am using matplotlib animate function. The movement looks fine. But I tried the following while loading the map. The map is not loading. Only a black patch is visible. I tried to specify the zorder as well. but nothing works.
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()
推荐答案
您可以使用 scipy.misc import imread
读取背景图像,并使用 plt.imshow
进行渲染动画的背景.
You can read background image with scipy.misc import imread
and use plt.imshow
to render in the background of your animation.
下面的示例生成一个圆(我们假设它是您的车),在背景中放置"usa_map.jpg",然后在地图上移动圆.
Below example generates a circle (we'll assume its your car), puts "usa_map.jpg" in the background and then moves circle over map.
奖励,您可以使用 anim.save('the_movie.mp4', writer 使用
ffmpeg
等编码器将动画保存为 mp4
格式的电影= 'ffmpeg', fps=30)
Bonus, you can save the animation using encoders such as ffmpeg
as a movie in mp4
format using anim.save('the_movie.mp4', writer = 'ffmpeg', fps=30)
源代码
import numpy as np
import matplotlib.pyplot as plt
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 = 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()
以上代码将生成带有在美国地图周围移动的圆的动画.它也将另存为'the_movie.mp4',我无法在此处上传.
Above code will generate animaton with a circle moving around USA map. It will also be saved as 'the_movie.mp4' , which I cant upload here.
结果图像
这篇关于使用matplotlib动画在后台显示地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!