我做了一个森林火灾的小动画。我的密码在问题的最后。在
代码forestfire.py
包含将把火蔓延到所有forest
的函数。然后forestfire_test.py
将forestfire.py
导入为ff
,然后我可以用鼠标点击matplotlib显示的数组来启动{
在我提问之前,这里有一些信息:
forest[i,j] = 0
forest[i,j] = 1
forest[i,j] = 2
forest[i,j] = 3
基本上,forest
是由1到0之间的数字组成的,大小为nxm的二维数组。函数onclick
点燃了forest
,而{spreadfire
也在蔓延。在
使用函数onclick
我可以让森林着火(如果我单击数组,树将变为红色),使用函数start
我可以执行代码,这要归功于按钮Start
。在
现在的问题是,我第一次执行代码时,它不知道什么是ani(NameError: global name 'ani' is not defined
)–这很正常,因为我甚至在调用函数start之前调用了动画ani
(通过尝试保存它)。但是如果我试图将ani
保存在函数start
中,我会得到一个空白的绘图——这也是正常的。在
总而言之,我需要在调用函数start
之后保存动画,但是我不能在函数start
的末尾保存它,否则我将得到一个空白的绘图。有人能告诉我该怎么做吗?在
PS:我使用Spyder和IPython控制台,如果我的解释不够清楚,请告诉我。在
import forestfire as ff
import numpy as np
import matplotlib.pylab as plt
import matplotlib.colors as mcolors
from matplotlib import cm
from matplotlib.widgets import Button, Cursor
global forest
forest = np.random.rand(100,100)
# Colormap
greens = cm.Greens(np.linspace(0,1, num=50))
greensfill = cm.Greens(np.ones(25))
red = [(1,0,0,1)]*len(greens)
gray = [(.5,.5,.5,1)]*len(greens)
colors = np.vstack((greens, greensfill, red, gray))
mycmap = mcolors.LinearSegmentedColormap.from_list('my_colormap', colors)
# Figure
fig, ax = plt.subplots(figsize=(10,5))
fig.subplots_adjust(right=1.3)
im = ax.imshow(forest, animated=True, cmap = mycmap, interpolation="none", origin='lower', vmin=0, vmax=3.5)
ax.set_xlabel("X")
ax.set_ylabel("Y")
ax.tick_params(direction='out')
cursor = Cursor(ax, useblit=True, color='red', linewidth=1)
plt.show()
# Coordinates
def onclick(event):
x, y = int(event.xdata), int(event.ydata)
forest[y,x] = 2.
im.set_data(forest)
fig.canvas.draw_idle()
fig.canvas.mpl_connect('button_press_event', onclick)
# Start button
def start(event):
global ani
ani = ff.forestfire(forest)
button_ax = plt.axes([0.15, 0.45, 0.2, 0.1])
button = Button(button_ax, 'Start', color='lightgrey', hovercolor='grey')
button.on_clicked(start)
# Animation
ani.save("forestfire_test.mp4", writer = 'ffmpeg', fps=5, dpi=500)
正如评论中提到的,这里有两个问题:
ani.save
。这是因为ani
只在按下开始按钮后定义。在plt.show
应该只在脚本末尾调用。在这样我就可以正常工作了,以脚本的形式运行(在Python2.7.10上,matplotlib 2.0.2上),因为单击“开始”按钮后,动画将作为mp4文件保存到当前目录中。在
除此之外,我需要将帧速率设置为6或更高,如a previous question中所注释的那样。在
相关问题 更多 >
编程相关推荐